Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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 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.

like image 530
helpermethod Avatar asked May 16 '10 08:05

helpermethod


1 Answers

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 ...)

like image 131
Stephen C Avatar answered Nov 15 '22 11:11

Stephen C