Sunday, September 11, 2011

Use Null Object instead of Null literals

Use Null Object instead of Null literals that reduce the extra overhead of checking whether the Object is created or not. Whenever you you want to access the object or access the properties of that object, you must have to check the object against the Null literals.

Sometime we heard that set some default value instead of null. There is no hard and fast rule for declaring all Objects with a default value.If we don't do then we have to take responsibility for exception NullPointerException.

So, I sugges to do Something for Nothing. This is not a new. If you go through the design patterns, you found that there is a Null Object Pattern. 

If a client calls a method on a field or variable that is null, an exception may be
raised, a system may crash, or similar problems may occur. To protect our systems from such unwanted behavior, we write checks to prevent null fields or
variables from being called and, if necessary, specify alternative behavior to
execute when nulls are encountered:

if (someObject != null)
  someObject.doSomething();
else
  performAlternativeBehavior();


Repeating such null logic in one or two places in a system isn’t a problem,
but repeating it in multiple places bloats a system with unnecessary code. Compared with code that is free of null logic, code that is full of it generally takes
longer to comprehend and requires more thinking about how to extend. Null
logic also fails to provide null protection for new code. So if new code is written
and programmers forget to include null logic for it, null errors can begin to
occur.


The Null Object pattern provides a solution to such problems. It removes
the need to check whether a field or variable is null by making it possible to
always call the field or variable safely. The trick is to assign the field or variable
to the right object at the right time. When a field or variable can be null, you
can make it refer to an instance of a Null Object, which provides do-nothing,
default, or harmless behavior. Later, the field or variable can be assigned to
something other than a Null Object. Until that happens, all invocations safely
route through the Null Object.



Kent Beck - father of eXtream Programming and JUnit and also contributor of Eclipse.suggested use of Null Object instead of Null literals.
Benefits and Liabilities
+ Prevents null errors without duplicating null logic.
+ Simplifies code by minimizing null tests.
– Complicates a design when a system needs few null tests.
– Can yield redundant null tests if programmers are unaware of a Null
Object implementation.
– Complicates maintenance. Null Objects that have a superclass must
override all newly inherited public methods.

No comments:

Post a Comment