Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a static "NULL" object in Java?

Tags:

java

null

While browsing through some code for a library I'm using, I came across this code snippet:

public class SomeClass {

     private static final class Null {
        /* ... */
     }

     public static final Object NULL = new Null();

}

Is this a common practice to have a special NULL object for a class that gets used instead of Java's null? What are the upsides to doing this instead of using Java's built in null?

The main reason I'm curious is that while using the library, I kept checking whether SomeClass was null, without realizing that they were using a special NULL object to denote a null object of SomeClass.

EDIT: For those wondering, the exact code from the source is:

public class JSONObject {
     private static final class Null {
        protected final Object clone() {
            return this;
        }
        public boolean equals(Object object) {
            return object == null || object == this;
        }
        public String toString() {
            return "null";
        }
    }

    public static final Object NULL = new Null();
}
like image 410
Ivan Avatar asked Oct 28 '11 20:10

Ivan


2 Answers

The null object pattern can occasionally be a useful one - so you don't use a null reference, but have an actual object with neutral behaviour. However, the implementation you've given there doesn't make sense:

  • Null doesn't extend SomeClass, which I'd expect it to
  • NULL is declared as Object, not SomeClass.

So as it is, I'd say that code is useless. But when implemented properly, the pattern can be useful.

like image 76
Jon Skeet Avatar answered Sep 24 '22 09:09

Jon Skeet


This is the "null object pattern". The advantage is that you don't have to explicitly check for null, avoiding NPEs.

like image 34
Dave Newton Avatar answered Sep 21 '22 09:09

Dave Newton