Upload
billhails
View
65
Download
0
Embed Size (px)
Citation preview
The Wrong Solution
$tenant = $house->getTenant();if ($tenant) { print $tenant->getName();} else { print “no tenant”;}
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();
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.
Salient Points
More generally the rule is: never return a nullwhen your client is expecting an object, returna Null Object instead.
Real Worldclass 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); }
Real Worldclass RealNode implements Node { private $left, $right; function copy() { return new self($left->copy(), $right->copy()); }
class NullNode implements Node { function copy() { return $this; }
Real World
• Objective C has the Null Object Pattern built-in!
• Calling a method on null in Objective C results in null.