10
Null Object Pattern Avoids null pointer exceptions. Replaces conditionals with polymorphism.

Null object

Embed Size (px)

Citation preview

Null Object PatternAvoids null pointer exceptions.

Replaces conditionals with polymorphism.

The Problem

print $house->getTenant()->getName();

Error!

Cannot call method on non-object.

“Name”

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.

Real World

• Fowler calls this the “Special Case Object” pattern.

• We can have alternative null objects for different circumstances, i.e.

• NoTennant

• UnknownTennant