views:

294

answers:

4

I've seen some developers put instance variable declarations at the end of classes though I mostly see them placed at the top. The only reasons I can think of for doing this are stylistic preference or maybe it somehow makes them easier to work with in an IDE. Is there a more legitimate reason for choosing this style?

+1  A: 

It's mostly (if not entirely) personal preference. I like them at the top, but I couldn't really give a better reason for it then that it's the way I'm used to.

Rik
+10  A: 

There is no particularly "good" reason for doing it one way or another. The only thing that really matters is that everyone on the same project does it the same way.

However, placing them at the top is far more common in my experience, and is the practice recommended by the Java style guidelines, so that's what I'd go with.

You can enforce your chosen convention with an automatic source code formatter such as Jalopy, or that which comes with Eclipse.

Don
+4  A: 

because of "Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18) (http://en.wikipedia.org/wiki/Design_Patterns#Introduction.2C_Chapter_1), some people prefer to declare instance variables at the bottom of the class. the theory being that the user of a class is more interested in what they can do with the the class (methods) as opposed to how something is done (variables). placing the methods at the top of the class exposes them first to the user when they look at the code.

Ray Tayek
A: 

Most instance variables are private, so I tend to put them at the bottom because I declare members in order of decreasing visibility. If I declared them in order of increasing visibility they would be at the top, which is also reasonable.

What I don't like is having private fields followed by public fields followed by private methods. If I am developing a client class I want all the public parts together (since that is all I am interested in.)

finnw