开发者

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

When I write a class in Java, I like to initialize the attributes which are set to a default value directly and attrib开发者_StackOverflow中文版utes which are set by the caller in the constructor, something like this:

public class Stack<E> {
    private List<E> list;
    private int 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?

EDIT:

I came up with that idea after reading the sources of LinkedList and ArrayList, which both clearly set their attributes (size in LinkedList and firstIndex/lastIndex in ArrayList) to 0.


There is no need to explicitly initialize a reference-typed attribute to null. It will be initialized to null by default. Similarly, there are default initialization rules for the primitive types:

  • boolean attributes are initialized to false, and
  • integral (including char), float and double attributes are all initialized to zero.

So the initialization of size in the example is also strictly unnecessary.

It is therefore purely a matter of style as to whether you do or do not initialize them. My personal opinion is that it does not improve readability, and therefore is a waste of time. (I don't write my code to be maintained by people who don't understand the basics of Java ...)


Since you are relying on these variables having the default value (0, null) for a new instance, I would initialise them to illustrate to the reader that this is the case. Otherwise they might have to read further to know there is no constructor where the variables are initialised (possibly to another value).

Edit: Of course, you are not required to initialise; I assume the question is about preferred style and this is my preference.


It's a personal preference but IMHO it is better to omit it. References are initialized with null by default so you're only cluttering the code. The less code the better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜