Should instance variables be declared at the top or bottom of a class?

POSITION OF CLASS FIELDS (aka INSTANCE VARIABLES)
Top of the Class Bottom of the Class

class Foo
{
    private int field1 ;
    private String field2 ;

    public int method1() ;
    public void method2() ;
} ;

class Foo
{
    public int method1() ;
    public void method2() ;

    private int field1 ;
    private String field2 ;
} ;
Java doesn't care where you declare the fields in your class.
Why Place Them At The Top of the Class? Why Place Them At The Bottom of the Class?

Putting instance variables at the bottom is like putting the basement on the 3rd floor.

The tradition of putting data declarations at the top of a class comes from the Pascal and the C languages, the compilers of which required them to be there.

If a programmer is writing a class then they need to know about the private and protected features. It is most helpful to have the instance variables at the top of the class.

If you are looking at a class then you are looking at the details of method bodies, and you need to know what the variables represent in order to understand the code.

Advocates of moving declarations to the bottom claim that the practice gets you thinking about the operations rather than the data first. However, in many cases you have already accomplished that by defining a Java interface for the operations. One of the primary concerns of an implementing class is the representation of the data, which the method implementations must also access and process.

Variables are at the bottom of the top-down "food chain".

It encourages you to think of encapsulation and data hiding when you can see methods before you see the variables. It gets you thinking about the operations rather than the data first.

Instance variables declared at the end of a class encourage abstraction -- i.e., a client of a class should not need to see any private or protected members -- either fields or methods. Have users look at the interfaces for classes (or alternatively the javadoc for classes). These should be provided with comments that make sense without having to reveal private information. With interfaces or with javadoc documenation, one is not distracted with things that are not supposed to be seen and hence they should form the best thing for users to look at to use the classes.


URL:   http://www.comscigate.com/    Last Revised:  November 3, 2007