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

Null object

Aug 05, 2015

Download

Technology

billhails
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Null object

Null Object PatternAvoids null pointer exceptions.

Replaces conditionals with polymorphism.

Page 2: Null object

The Problem

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

Error!

Cannot call method on non-object.

“Name”

Page 3: Null object

The Wrong Solution

$tenant = $house->getTenant();if ($tenant) { print $tenant->getName();} else { print “no tenant”;}

Page 4: Null object

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();

Page 5: Null object

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.

Page 6: Null object

Salient Points

More generally the rule is: never return a nullwhen your client is expecting an object, returna Null Object instead.

Page 7: Null object

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); }

Page 8: Null object

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; }

Page 9: Null object

Real World

• Objective C has the Null Object Pattern built-in!

• Calling a method on null in Objective C results in null.

Page 10: Null object

Real World

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

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

• NoTennant

• UnknownTennant