Practical PHP Refactoring: Hide Delegate
Join the DZone community and get the full member experience.
Join For FreeThe client code is calling a method on a collaborator (delegate) of another object, obtained by getter or another sequence of calls. Hide Delegate is about respecting the Law of Demeter: don't talk to strangers, by avoiding relying objects which are not directly in the surroundings of the current one.
In this refactoring, the delegate class is hidden by replicating the used part of its protocol on the upper level class; this is just one of the ways to conform to the law, not the only one.
Why another law?
We all know the private fields mantra, which says no public field must be exposed in object-oriented programming. However, exposing all private fields via getters is no improvement.
I'm ok with getter for almost scalars, as you need to expose them in some way (although there are alternatives.) But the problem with getters is that soon the client code will call another method on the returned object, and then another method on the returned object of the former method, and navigate the whole object graph.
In that case, the client code makes assumption over the whole graph surrounding the $this:
$object = $this->collaborator->getOtherObject(); $anotherObject = $object->getAnotherObject(); $field = $anotherObject->getSomeField(); // do some work with $field
Testing code which makes all these assumptions is a mess; and any change in one of those objects would have a ripple up to this client code: changing getSomeField() name or signature imposes a change in $this, a distant object. Encapsulation is about avoiding these ripples.
We can avoid spreading the knowledge of the whole graph in a single object via delegation:

(This graphical representation of objects is inspired by Growing Object-Oriented Software.)
Steps
In Fowler's terminology, the client object is calling the server object, which returns a delegate that thus has been exposed. In the initial state, other methods are called on the delegate.
- Create a delegation method on the server object; the server already references delegate, which should already be there on $this, and thus the delegation method should be simple to write.
- Adjust client calls to use the server's new method.
- Execute tests at the functional level; unit tests of the client should change (or be introduced: now you can use a Test Double easily, because isolating the client from the real graph is not going to require an alternate graph mimicking all the real one, just a Test Double for the server Facade).
The invasive effect is on client's code in this refactoring: the server only gains a method, while the delegate should not be touched at all.
Example
In the initial state, the Delegate is handed out to the Client, the UserController class.
<?php class HideDelegate extends PHPUnit_Framework_TestCase { /** * We are imagine an User is registered and an activation number is sent * via mail to him. This test regards the activation process enacted * by a user following a link in the mail. */ public function testUserIsActivatedIfActivationTokenIsCorrect() { $userCollection = new UserCollection(array( 'giorgio' => new User('giorgio', 42) )); $controller = new UserController($userCollection); $controller->activation(array( 'name' => 'giorgio', 'activationNumber' => 42 )); $this->assertTrue($userCollection->getUser('giorgio')->isActive()); } } /** * The Delegate: This class contains the business logic. */ class User { private $name; private $activationNumber; private $active = false; public function __construct($name, $activationNumber) { $this->name = $name; $this->activationNumber = $activationNumber; } public function activate($number) { if ($this->activationNumber == $number) { $this->active = true; } } public function isActive() { return $this->active; } } /** * The Server: this class hands out a User instance. */ class UserCollection { private $users; public function __construct(array $users) { $this->users = $users; } public function getUser($name) { return $this->users[$name]; } } /** * The Client: this class gets an User instance and calls a method on it, * violating the Law of Demeter. */ class UserController { private $userCollection; public function __construct(UserCollection $collection) { $this->userCollection = $collection; } public function activation(array $request) { if (!isset($request['name'])) { throw new InvalidArgumentException('No user specified.'); } if (!isset($request['activationNumber'])) { throw new InvalidArgumentException('No activation number.'); } $user = $this->userCollection->getUser($request['name']); $user->activate($request['activationNumber']); } }
We add a delegation method so that Server is not forced to return a User object for this use case:
/** * The Server: this class hands out a User instance. */ class UserCollection { private $users; public function __construct(array $users) { $this->users = $users; } public function getUser($name) { return $this->users[$name]; } public function activationOfUser($name, $activationNumber) { $this->users[$name]->activate($activationNumber); } }
Now we can change the Client code to call the new delegation method. Meanwhile, the functional test is still passing.
class UserController { private $userCollection; public function __construct(UserCollection $collection) { $this->userCollection = $collection; } public function activation(array $request) { if (!isset($request['name'])) { throw new InvalidArgumentException('No user specified.'); } if (!isset($request['activationNumber'])) { throw new InvalidArgumentException('No activation number.'); } $this->userCollection->activationOfUser($request['name'], $request['activationNumber']); } }
We could go on by breaking up the test in two unit tests: one which tests the logic on UserCollection, and one which tests the delegation of UserController to a Test Double of UserCollection.
Opinions expressed by DZone contributors are their own.
Comments