

Handling Associations on Null Objects in Rails - rabidferret
http://robots.thoughtbot.com/handling-associations-on-null-objects

======
thangalin
[http://www.infoq.com/presentations/Null-References-The-
Billi...](http://www.infoq.com/presentations/Null-References-The-Billion-
Dollar-Mistake-Tony-Hoare)

I often see code such as:

    
    
        public Object getObject() {
          return this.object;
        }
    

I favour lazy initialization combined with self-encapsulation:

    
    
        private Object getObject() {
          Object o = this.object;
    
          if( o == null ) {
            o = createObject();
            this.object = o;
          }
    
          return o;
        }
    

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.

It could even be implemented as a language feature:

    
    
        public class C {
          nullsafe String name;
    
          public void greeting() {
            System.out.printf( "Hello, %s\n", getName() );
          }
        }
    

Where the "nullsafe" keyword automatically generates a private accessor and
corresponding protected creation method.

~~~
sitkack
Bah! I know the JVM is now double-check-locking safe but
[http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLo...](http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html)

Just put a `synchronized` on it and call it good. The JVM is so damn fast,
_nearly_ all the stuff in the Haggar book (Practical Java) is not applicable
anymore.

------
sitkack
The null object is a beautiful device.
[http://en.wikipedia.org/wiki/Initial_object](http://en.wikipedia.org/wiki/Initial_object)

