Friday, September 9, 2011

understanding NULL Pattern

It is easy to miss a NULL check in our code especially when the code is not fully tested. Will it be nice to call one object's property or method without checking if the object is NULL or not without throwing NullReferenceException? The answer is to implement NULL pattern.

How?

Creat an interface for your real and null-check classes. In the real class, do real implementations. In the other null-check class, put in same signatures as the real one, but with no code, or return some default values. The callers would interact with the interfaces only. If the object is null, by calling its method, the null-check class will just do nothing or return default values. As a result, your code would have lot less IF tests for NULL references, and look more elegant and compact. 

However, doing null pattern will create more work initially. 

Here is the useful reference where I learned all about this - http://sourcemaking.com/design_patterns/null_object

No comments:

Post a Comment