Class members ordering convention

When creating a class with several members at some point we come to the decision how to order the members. For example let's take the following Java class:

public class MyClass {

    public MyClass(int initialCount) {
        setCount(initialCount);
    }
   
    public static final String MY_STRING = "MY_STRING";
   
    private int mCount;
   
    private void setCount(int count) {
        mCount = count;
    }
   
    public int getCount() {
        return mCount;
    }
   
    public int mIncrement = 1;
   
    public int getNextCount() {
        setCount(getCount() + mIncrement);
        return getCount();
    }
   
}


Now some people order the members alphabetically, others just list them in order of creation - just put the newest members at the end. There's however useful convention how to do this. Fields go on top - first the static fields, then the public ones and last the private ones. Next are the constructors, followed by the public methods and at the end private methods. Now out class looks like:

public class MyClass {

    public static final String MY_STRING = "MY_STRING";
   
    public int mIncrement = 1;
   
    private int mCount;
   
    public MyClass(int initialCount) {
        setCount(initialCount);
    }
   
    public int getCount() {
        return mCount;
    }
   
    public int getNextCount() {
        setCount(getCount() + mIncrement);
        return getCount();
    }

    private void setCount(int count) {
        mCount = count;
    }
}

 

No comments yet

Back to articles list

This page was last modified on 2024-03-26 15:26:03