views:

124

answers:

2

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.

+4  A: 

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
+1, exactly what I wanted to write.
Zenzen
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
+3  A: 

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
Half of the problem with Java is how people use it. Be a Java Heretic (as long as your code is clear and consistent).
Peter DeWeese
I understand I'm free to ignore it, I'm just curious why it was agreed on in the first place.
Tom Tresansky
Because getters and setters are just methods. Even if they mean something specific, they still are simple methods.
Colin Hebert