Variable declaration placement
I'm working on a slightly intricate GUI program with a lot of JButtons, JTextFields, and the sort. In classes, all the examples were written as such:
Code :
public class Foo
{
private JTextField text1;
private JTextField text2;
private JLabel label1;
private JLabel label2;
private JButton button1;
private JButton button2;
//constructors
//other methods
}
While working on this project, I have found myself doing the following instead:
Code :
public class Foo
{
public Foo( )
{
JTextArea = new JTextArea( );
//so on and so forth for every object needed...
}
//other methods
}
I have seen it in some places where, all the variables being private, they are placed at the bottom of the code:
Code :
public class Foo
{
//constructors
//other methods
private JTextField;
private JTextArea;
private JButton;
//so on and so on...
}
Which way do you use and what pro's and con's are there to each method?
Re: Variable declaration placement
Myself, I usually place GUI instance variables at the bottom, as there can be so many of them, which would push code too far down for my preference.
I believe, cannot be 100% sure, that it is all up to your personal style/preference.
Placing at the bottom I suppose puts the interface as the main focus. I usually always declare my instance variables up-top for non-GUI programs, or for very small GUI programs, though.
(This is all from making Toy-Programs though, can't speak on a professional (or accurate?) level.)
Re: Variable declaration placement
Many years ago sun/oracle laid out code conventions for java (see Code conventions) which state that instance variables be at the top (above the constructor) in the order of public, protected, private (see Class Declarations). You may choose to follow or not follow the rules, but even for things like posting code snippets on forums such as this, code that don't follow the rules may not help your chance at receiving replies. Many a time I have had to refactor code that doesn't follow the convention, and it is a royal pain in the you know what.