Null Check


  • There are repeated occurrences of code like this:

     if (xxx == null) ... 


Someone decides, "We'll use null to mean the default." This may let them avoid the trouble of initializing certain fields or of creating certain objects, or it may be an afterthought for an unexpected case. The null check may be introduced to work around a null-pointer bug (without addressing the underlying cause).

What to Do

  • If there's a reasonable default value, use that.

  • Otherwise, Introduce Null Object to create a default object that you explicitly use.


Reduces duplication. Reduces logic errors and exceptions.


  • If the null check occurs in only one place (e.g., in a factory method), it is usually not worth the effort to create a separate Null Object.

  • Null objects need to have safe behavior for the methods they provide. They often act like identity objects (as 0 does relative to addition). If you can't define a safe behavior for each method, you may not be able to use a Null Object.

  • Watch out for a case where null means two or more different things in different contexts. (You may be able to support this with different Null Objects.)

Exercise 20 Null Object.

Consider the code in Exercise 4 (Chapter 3).

  1. Some of the null checks are checks for null strings. One alternate approach would be to use empty strings. What are the downsides of this approach (taking into account the test and all the other client classes you don't see here)?

  2. What's another approach to this problem?

  3. Extract a Bin class, and introduce a Null object.

See Appendix A for solutions.

Refactoring Workbook
Refactoring Workbook
ISBN: 0321109295
EAN: 2147483647
Year: 2003
Pages: 146

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: