<a href="http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare" rel="nofollow">http://www.infoq.com/presentations/Null-References-The-Billi...</a><p>I often see code such as:<p><pre><code> public Object getObject() {
return this.object;
}
</code></pre>
I favour lazy initialization combined with self-encapsulation:<p><pre><code> private Object getObject() {
Object o = this.object;
if( o == null ) {
o = createObject();
this.object = o;
}
return o;
}
</code></pre>
This is thread-safe and allows injecting new behaviour via polymorphism (overriding the "create" methods in a subclass), which adheres to the Open-Closed Principle. It also eliminates the possibility of accidentally dereferencing nulls.<p>It could even be implemented as a language feature:<p><pre><code> public class C {
nullsafe String name;
public void greeting() {
System.out.printf( "Hello, %s\n", getName() );
}
}
</code></pre>
Where the "nullsafe" keyword automatically generates a private accessor and corresponding protected creation method.
The null object is a beautiful device. <a href="http://en.wikipedia.org/wiki/Initial_object" rel="nofollow">http://en.wikipedia.org/wiki/Initial_object</a>