4

Why is it convention to place getters and setters after constructors within classes?

I would rather see them placed immediately after class fields, before the constructors, in order to see which of the private fields are accessible via getter & setter methods. Especially if the methods' bodies are single return or assignment statements.

Tom Tresansky
  • 19,364
  • 17
  • 93
  • 129
  • 2
    I think most java ide's will let you view the "structure" of the class you're in, usually in a side bar. This makes it easy to see what methods are available. – Zachary Wright Aug 31 '10 at 13:24

2 Answers2

9

The Java coding convention states that methods (getters and setters are methods) should be after constructors declarations. It just a convention and it exists to make code easier to read in general.

If you judge that the code is more readable with getters//setters after fields rather than after constructor, you're free to do it.


Resources :

Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
6

My take is that you have fields, then constructors, then methods so you can read through the class saying: "this is what makes up the object, this is how you build it, and having built-it here's what you can do with it".

That said, it's entirely subjective. If another layout makes sense for you and your team in your domain of interest, then do it differently. The only thing you should be wary of is making sure that your projects are internally consistent. It can be very off-putting to see code style change class-by-class.

GaryF
  • 23,950
  • 10
  • 60
  • 73
  • I doubt it is entirely subjective. There was probably a good reason why Sun decided on the convention, and I'm curious as to what it was. – Tom Tresansky Aug 31 '10 at 14:13