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?
Instance variables are declared in a class, but outside a method, constructor or any block. When space is allocated for an object in the heap, a slot for each instance variable value is created.
An instance variable is a variable which is declared in a class but outside of constructors, methods, or blocks. Instance variables are created when an object is instantiated, and are accessible to all the constructors, methods, or blocks in the class.
It's best to declare variables when you first use them to ensure that they are always initialized to some valid value and that their intended use is always apparent. The alternative is typically to declare all variables in one location, typically at the top of the block or, even worse, at the top of a function.
Instance variables are declared with the keyword “private” by default. However, it is possible to make an instance variable public or protected. The value of an instance variable can be changed only within the method in which it is declared.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With