Avoid Null Checks
Damien Cassou, Stéphane Ducasse and Luc Fabresse
http://stephane.ducasse.free.fr
Anti If Campaign
Branching (with if
) based on the type of an object is bad:
- adding a new type requires modifying all such code
- methods will become very long and full of details
Send messages instead
Anti If Campaign
Branching (with if
) based on the type of an object is bad
- adding a new type requires modifying all such code
- methods will become very long and full of details
Send messages instead
Do Not Return Nil
ifTrue: [ ^ nil ]
forces every client to check for nil
:
Return Polymorphic Objects
When possible, replace if
by polymorphic objects:
- when returning a collection, return an empty one
- when returning a number, return 0
Your clients can just iterate and manipulate the returned value
For Exceptional Cases, Use Exceptions
For exceptional cases, replace nil
by exceptions:
- avoid error codes because they require
if
in clients
- exceptions may be handled by the client, or the client's client, or ...
Initialize Your Object State
Avoid nil
checks by initializing your variables
- by default instance variables are initialized with
nil
Use Lazy Initialization if Necessary
You can defer initialization of a variable to its first use:
Sometimes you have to check...
Sometimes you have to check before doing an action
- if you can, turn the default case into an object
Use NullObject
- a null object proposes a polymorphic API and embeds default actions/values
- Woolf, Bobby (1998). "Null Object". In Pattern Languages of Program Design 3. Addison-Wesley.
Conclusion
- A message acts as a better
if
- Avoid null checks, return polymorphic objects instead
- Initialize your variables
- If you can, create objects representing default behavior
/