To "null" or not to "null" my class's attributes

Posted by Helper Method on Stack Overflow See other posts from Stack Overflow or by Helper Method
Published on 2010-05-16T08:57:10Z Indexed on 2010/05/16 9:00 UTC
Read the original article Hit count: 218

Filed under:
|

When I write a class in Java, I like to initialize the attributes which are set to a default value directly and attributes which are set by the caller in the constructor, something like this:

public class Stack<E> {
    private List<E> list;
    private size = 0;

    public Stack(int initialCapacity) {
        list = new ArrayList<E>(initialCapacity);
    }

    // remainder omitted
}

Now suppose I have a Tree class:

public class Tree<E> {
    private Node<E> root = null;

    // no constructor needed, remainder omitted
}

Shall I set the root attribute to null, to mark that it is set to null by default, or omit the null value?

© Stack Overflow or respective owner

Related posts about best-practices

Related posts about java