Practical PHP Refactoring: Replace Constructor with Factory Method
Join the DZone community and get the full member experience.
Join For FreeIn the scenario of today, we have a complex constructor: read this definition as anything that does more work than assigning parameters to fields.
The solution proposed by this refactoring is replacing direct calls to the constructor with a bit of indirection: a Factory Method. This method will often be static, and placed the class itself. When appropriate, it will completely hide the constructor, which will be then defined as private.
The GoF pattern also comprehends Factory Methods which are hooks for Template Methods: their goal is to be overridden via subclassing for configuring what and how to instantiate. That pattern isn't necessarily related to this refactoring.
Why an indirection over new()?
There are many different reasons to use a Factory Method.
First, it allows reuse of the object without triggering the logic modelled into the constructor. In a test suite, this is fundamental and Google engineers cites simple constructors in its guide for writing testable code.
Second, a Factory Method gives a name to the constructor operation; in a classic example, new Area(0, 20, 100, 220) becomes a readable call Area::fromXYtoXY(0, 20, 100, 220). Value Objects work very well with this pattern.
Third, Factory Methods allow subclassing: they can return an instance of a subclass, while a constructor can't.
We'll see the static method case as it is self-contained and fits very well into an article. The GoF case is just the same mechanic applied to a method on the client class.
Static Factory Methods, especially for Value Objects, are one of the few usages of the static keyword that I concede myself. A problem with *static* methods is that they cannot use collaborators: consider a Factory object if the Factory Method grows.
Steps
- Create a Factory Method, delegating to the constructor.
- Replace calls to new() with calls to the Factory Method, which just delegates to the constructor.
- Change the constructor's scope to private if you do not need it for testing.
- Move code which pertains only to the Factory Method outside of the constructor. If you do not reuse the constructor, it is functionally equivalent, so just put it where it feels better (or where you would look for it).
For example, every reference to $this must stay in the constructor; heavyweight operations on the input parameters reside better in the Factory Method so that you can test the object by creating it quickly a known configuration with new().
Example
The example is related to an Area object, which I used in object tracking software. It represents an Area of an image; just the rectangle's dimensions and position, and not the content in pixels.
Area is a classic Value Object with a related algebra: I would intersecate areas, breaking them up in several subareas, extend them a few pixels, or move them on the image at a certain speed. There are several ways to create an Area. The constructor models two use cases:
- two opposite corners are given. A rectangle is uniquely determined.
- an Area is built around a center point, of a particular size (square by default.)
<?php class ReplaceConstructorWithFactoryMethod extends PHPUnit_Framework_TestCase { public function testAnAreaIsCreatedGivenTheTwoOppositeCorners() { $area = new Area(1, 11, 100, 210); $this->assertEquals(20000, $area->measure()); } public function testAnAreaIsCreatedAroundAPoint() { $area = new Area(400, 500, 100); $this->assertEquals(10000, $area->measure()); } } class Area { private $first_corner_x; private $first_corner_y; private $second_corner_x; private $second_corner_y; public function __construct($first_x, $first_y, $second_x, $second_y = null) { if ($second_y === null) { $size = $second_x; $this->first_corner_x = $first_x - $size / 2 + 1; $this->first_corner_y = $first_y - $size / 2 + 1; $this->second_corner_x = $first_x + $size / 2; $this->second_corner_y = $first_y + $size / 2; } else { $this->first_corner_x = $first_x; $this->first_corner_y = $first_y; $this->second_corner_x = $second_x; $this->second_corner_y = $second_y; } } public function measure() { $width = $this->second_corner_x - $this->first_corner_x + 1; $height = $this->second_corner_y - $this->first_corner_y + 1; return $width * $height; } }
We're going to write a Factory Method for the first use case.
class Area { /* ... */ public static function fromXYtoXY($first_x, $first_y, $second_x, $second_y) { return new self($first_x, $first_y, $second_x, $second_y); } }
And now for the second use case. Right now, these methods just call new() and are syntactic sugar.
class Area { /* ... */ public static function fromXYtoXY($first_x, $first_y, $second_x, $second_y) { return new self($first_x, $first_y, $second_x, $second_y); } public static function fromCenterAndDimension($center_x, $center_y, $dimension) { return new self($center_x, $center_y, $dimension); } }
Now we can extract some code from the constructor, and uniform its parameters.
<?php class ReplaceConstructorWithFactoryMethod extends PHPUnit_Framework_TestCase { public function testAnAreaIsCreatedGivenTheTwoOppositeCorners() { $area = Area::fromXYtoXY(1, 11, 100, 210); $this->assertEquals(20000, $area->measure()); } public function testAnAreaIsCreatedAroundAPoint() { $area = Area::fromCenterAndDimension(400, 500, 100); $this->assertEquals(10000, $area->measure()); } } class Area { private $first_corner_x; private $first_corner_y; private $second_corner_x; private $second_corner_y; public function __construct($first_x, $first_y, $second_x, $second_y) { $this->first_corner_x = $first_x; $this->first_corner_y = $first_y; $this->second_corner_x = $second_x; $this->second_corner_y = $second_y; } public static function fromXYtoXY($first_x, $first_y, $second_x, $second_y) { return new self($first_x, $first_y, $second_x, $second_y); } public static function fromCenterAndDimension($center_x, $center_y, $dimension) { $first_x = $center_x - $dimension / 2 + 1; $first_y = $center_y - $dimension / 2 + 1; $second_x = $center_x + $dimension / 2; $second_y = $center_y + $dimension / 2; return new self($first_x, $first_y, $second_x, $second_y); } public function measure() { $width = $this->second_corner_x - $this->first_corner_x + 1; $height = $this->second_corner_y - $this->first_corner_y + 1; return $width * $height; } }
We make the constructor private, as the Factory Methods cover the use cases we use in testing and we don't need to call new() directly.
class Area { private $first_corner_x; private $first_corner_y; private $second_corner_x; private $second_corner_y; private function __construct($first_x, $first_y, $second_x, $second_y) { $this->first_corner_x = $first_x; $this->first_corner_y = $first_y; $this->second_corner_x = $second_x; $this->second_corner_y = $second_y; } /* ... */ }
Now it's a lot easier to understand how to instantiate the object by looking at the available Factory Methods; it's also faster to signal errors by separating only a few strict method signatures.
Opinions expressed by DZone contributors are their own.
Trending
-
Testing Applications With JPA Buddy and Testcontainers
-
Measuring Service Performance: The Whys and Hows
-
DevOps Pipeline and Its Essential Tools
-
How To Backup and Restore a PostgreSQL Database
Comments