Introduce Null Object
From CSSEMediaWiki
(Difference between revisions)
m |
|||
Line 3: | Line 3: | ||
== Motivation == | == Motivation == | ||
− | + | If you have repeated checks for a null reference, because one can't invoke anything on a null reference. | |
− | For example your code | + | For example your code looks like: |
− | if (customer == null) plan = BillingPlan.basic(); | + | if (customer == null) |
− | else plan = customer.getPlan(); | + | plan = BillingPlan.basic(); |
+ | else | ||
+ | plan = customer.getPlan(); | ||
+ | |||
+ | This pattern can also be used to act as a stub for testing if a certain feature, such as a database, is not available for testing. | ||
== Solution == | == Solution == | ||
− | Replace your check for a null | + | Replace your check for a null reference with a null object |
[[Image:Null Object.jpg]] | [[Image:Null Object.jpg]] | ||
Line 20: | Line 24: | ||
* Find all places that can give out a null value when asked for an object of the superclass and replace them to give a null object instead. | * Find all places that can give out a null value when asked for an object of the superclass and replace them to give a null object instead. | ||
* Find all places that compare a variable of the superclass type with null and replace them with a call to isNull(). | * Find all places that compare a variable of the superclass type with null and replace them with a call to isNull(). | ||
+ | |||
+ | The advantage of this approach over a working default implementation is that a null bbject is predictable and has no side effects: it does nothing. |
Revision as of 10:04, 4 October 2008
Summarised from Refactoring Martin Fowler 1999
Motivation
If you have repeated checks for a null reference, because one can't invoke anything on a null reference.
For example your code looks like:
if (customer == null) plan = BillingPlan.basic(); else plan = customer.getPlan();
This pattern can also be used to act as a stub for testing if a certain feature, such as a database, is not available for testing.
Solution
Replace your check for a null reference with a null object
- Create a subclass that acts as a null version of the class.
- Create an isNull() method in both classes. For the superclass it should return "false", and "true" for the subclass.
- Find all places that can give out a null value when asked for an object of the superclass and replace them to give a null object instead.
- Find all places that compare a variable of the superclass type with null and replace them with a call to isNull().
The advantage of this approach over a working default implementation is that a null bbject is predictable and has no side effects: it does nothing.