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();
}
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 toNULL
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.
This is the "null object pattern". The advantage is that you don't have to explicitly check for null, avoiding NPEs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With