Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placement of instance variable declarations

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?

like image 703
hydeph Avatar asked Oct 20 '08 14:10

hydeph


People also ask

Where should instance variables be declared?

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.

How are instance variables declared?

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.

Should variables be declared at the top?

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.

What should instance variables be declared as?

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.


3 Answers

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.

like image 125
Ray Tayek Avatar answered Sep 24 '22 07:09

Ray Tayek


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.

like image 32
Dónal Avatar answered Sep 26 '22 07:09

Dónal


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.

like image 24
Rik Avatar answered Sep 25 '22 07:09

Rik