Practical PHP Refactoring: Replace Type Code with State or Strategy
Join the DZone community and get the full member experience.
Join For Free- First, we saw a case where no behavior was modified by the type code values: the type code could be substituted by a single class.
- Second, we saw a case where behavior changed: we substituted the different type codes with subclasses of the original class.
- In the third case, that we'll see today, some behavior depends on the type code but extending the current class is not possible (because subclassing has been already been used, or as a design choice). This refactoring uses composition instead of inheritance.
What changes from the other two refactorings?
We can make a quick comparison with the other two solutions.
By replacing the type code with a single class, you already use composition and define a type replacing the type code. That type now could be an interface or abstract class, while it was a concrete class in the first refactoring.
By replacing the type code with subclasses, you are using multiple subtypes to model different behavior, eliminating conditional structures like ifs and switch. But in this refactoring they will be subtypes of an external class, not of the original one.
The class you create representing the type code is an implementation of the State or Strategy pattern. In the State case, the object changes often its class, returning a new instance. In the Strategy case, the object changes rarely, and the different implementations contain different algorithms or policies.
Why composing type code objects?
A prerequisite for this refactoring is that different behaviors should be dependent on the type code value.Moreover, one or more of these conditions should apply:
- subclassing is not available due to an already existing hierarchy, or not self-explaining as the class names are unclear and sound forced.
- The life cycle of the object is not on your control, so you can't instantiate the subclasses.
- The type code changes often, and reinstantiating the right class is a mess for technical reasons (such as your framework or your ORM).
Steps
The steps for applying this refactoring are similar to the Replace Type Code with Subclasses case, but this time they have to be applied to the State or Strategy object instead that on the main class.- First, you have to self-encapsulate the type code.
- Then, create a new class as the State object. Start to apply the previous refactoring on it, which means...
- Add a subclass of the State object for each value of the type code.
- The getTypeCode() in the original class should be delegated to the state object, which has to be created and saved in a field. Each subclass should override the method by providing its own value.
Example
In the initial state, there is some business logic identical to the Replace Type Code with Subclasses example, which depends on the type code value.<?php class ReplaceTypeCodeWithState extends PHPUnit_Framework_TestCase { public function testAnUserCanBeANewbie() { $user = new User("Giorgio", User::NEWBIE); $this->assertEquals("Giorgio", $user->__toString()); } public function testAnUserCanBeRegardedAsAGuru() { $user = new User("Giorgio", User::GURU); $this->assertEquals("ADMIN: Giorgio", $user->__toString()); } } class User { const NEWBIE = 'N'; const GURU = 'G'; private $name; private $rank; public function __construct($name, $rank) { $this->name = $name; $this->rank = $rank; } public function __toString() { if ($this->rank == self::GURU) { return "ADMIN: $this->name"; } // self::NEWBIE return $this->name; } }We start with self-encapsulation of the rank type code.
class User { const NEWBIE = 'N'; const GURU = 'G'; private $name; private $rank; public function __construct($name, $rank) { $this->name = $name; $this->rank = $rank; } protected function getRank() { return $this->rank; } public function __toString() { if ($this->getRank() == self::GURU) { return "ADMIN: $this->name"; } // self::NEWBIE return $this->name; } }We add a Rank class.
class Rank { public abstract function getCode(); }We add the subclasses NewbieRank and GuruRank, and then transform the private field into a Rank instance instead of a string type code.
class User { const NEWBIE = 'N'; const GURU = 'G'; private $name; private $rank; public function __construct($name, Rank $rank) { $this->name = $name; $this->rank = $rank; } protected function getRank() { return $this->rank->getCode(); } public function __toString() { if ($this->getRank() == self::GURU) { return "ADMIN: $this->name"; } // self::NEWBIE return $this->name; } } class Rank { public abstract function getCode(); } class NewbieRank { public function getCode() { return User::NEWBIE; } } class GuruRank { public function getCode() { return User::GURU; } }We can now move the variable logic of __toString() into the subclasses. Article updated: the Rank subclasses were missing the extends keyword.
<?php class ReplaceTypeCodeWithState extends PHPUnit_Framework_TestCase { public function testAnUserCanBeANewbie() { $user = new User("Giorgio", new NewbieRank); $this->assertEquals("Giorgio", $user->__toString()); } public function testAnUserCanBeRegardedAsAGuru() { $user = new User("Giorgio", new GuruRank); $this->assertEquals("ADMIN: Giorgio", $user->__toString()); } } class User { const NEWBIE = 'N'; const GURU = 'G'; private $name; private $rank; public function __construct($name, Rank $rank) { $this->name = $name; $this->rank = $rank; } protected function getRank() { return $this->rank->getCode(); } public function __toString() { return $this->rank->label() . $this->name; } } abstract class Rank { public abstract function getCode(); public abstract function label(); } class NewbieRank extends Rank { public function getCode() { return User::NEWBIE; } public function label() { return ''; } } class GuruRank extends Rank { public function getCode() { return User::GURU; } public function label() { return 'ADMIN: '; } }
After having moved the variable logic into the Rank hierarchy, we could again remove the getCode() method if not required anymore. We can also turn Rank into an interface, if it is stabilized as a purely abstract class without any code.
Opinions expressed by DZone contributors are their own.
Trending
-
Automated Multi-Repo IBM App Connect Enterprise BAR Builds
-
What Is End-To-End Testing? E2E Testing Tutorial With Examples and Best Practices
-
Apache Cassandra With Java: Introduction to UDT
-
How To Backup and Restore a PostgreSQL Database
Comments