2. The Problem
“Name”
print $house->getTenant()->getName();
Error!
Cannot call method on non-object.
3. The Wrong Solution
$tenant = $house->getTenant();
if ($tenant) {
print $tenant->getName();
} else {
print “no tenant”;
}
4. The Null Object Solution
class House {
private $tenant;
function getTenant() {
return $this.tenant
?: NullTenant::getInstance();
}
class NullTenant implements Tenant {
function getName() {
return “no tenant”;
}
print $house->getTenant()->getName();
5. Salient Points
• Null Objects are Singletons
• Null Objects keep no state.
• Null Objects implement the same interface as the
“real” objects.
• Null Objects “do the right thing” when a null is
expected.
6. Salient Points
More generally the rule is: never return a null
when your client is expecting an object, return
a Null Object instead.
7. Real World
class Node {
private $left, $right;
function copy() {
$leftcopy = $this->left
? $this->left->copy();
: null;
$rightcopy = $this->right
? $this->right->copy();
: null;
return new self($leftcopy,
$rightcopy);
}
8. Real World
class RealNode implements Node {
private $left, $right;
function copy() {
return new self($left->copy(),
$right->copy());
}
class NullNode implements Node {
function copy() {
return $this;
}
9. Real World
• Objective C has the Null Object Pattern built-in!
• Calling a method on null in Objective C results in
null.
10. Real World
• Fowler calls this the “Special Case Object” pattern.
• We can have alternative null objects for different
circumstances, i.e.
• NoTennant
• UnknownTennant