By convention, member and static variables should be defined first, at the top of a class, not scattered through it.  Developers will look for the member variable definitions at the top of the class, and failure to put it there will cause initial confusion.

Member variables must also be prefixed by private/public/protected to indicate how visible they are to other classes.

public class MyClass
{
    int totalValue = 0;

    public MyClass() {}

    boolean selected = "";
    String name = "";
    :  

In the above example, the reader has no clue of the visibility intentions of the author.  Did they simply forget to put visibility qualifiers on totalValue, selected and name?  Another quality problem is that the constructor is haphazardly mixed in between the variables, perhaps a mistake, probably not intentional.

Further analysis shows that the visibility of each variable needs to be different.

public class MyClass
{
    public int totalValue = 0;
    protected boolean selected = "";
    private String name = "";

    public MyClass(){}
    :

The uses of the different variable qualifiers are shown in the following table.

Qualifier

Meaning

private

My value is changed only within this class.  I am supposed to be hidden from direct access by others.

protected

My value is designed to be accessed and changed by other classes in the same package and by subclasses.

public

My value is designed to be read or modified by any other class, anytime.

Tip: If in doubt, make member variables private and restrict access.  You can always open up access later.

blog comments powered by Disqus