Question

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?

Was it helpful?

Solution

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 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.

OTHER TIPS

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.

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.

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.)

I've always rationalized that if you have a private class level variable, then you've either hardcoded a configuration, or you're tracking state one way or another. If you're tracking state, then 1) that should be made obvious to everyone who's going to write code in the file from the moment they open the file, and 2) tracking lots of states is a huge code smell, and if my devs are doing that, then I want it to be obvious. So putting it at the top, imho, makes bad code more obvious, and serves as a warning for future people who edit the class.

Definitely separate your public/protected vs private fields and members though, because people interested in one, likely aren't interested in the other.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top