Agile Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 635 posts at DZone. You can read more from them at their website. View Full User Profile

Practical PHP Refactoring: Remove Middle Man

08.01.2011
| 4930 views |
  • submit to reddit

Last week we talk about Hide Delegate as a tool for conforming to the Law of Demeter, and avoiding continuously scavenging the object graph in all directions. Another way for following this law does not consist in delegation, but in reorganizing the field references to other objects: the Remove Middle Man refactoring.

We will use the same terminology as for the Hide Delegate refactoring: one or more Clients access a Delegate object by passing through a Server object which returns a reference to it. In this case the Server is also called Middle Man.

With Remove Middle Man, we start referencing directly the Delegate from the Client, with a private field. The refactoring decouples the contract with the delegate from the rest of the nearby graph. The disadvantage of Hide Delegate was that the contract (e.g. public methods) of the Server changes multiple times to accomodate part of the Delegate's one.

Some gotchas

Remove Middle Man does not necessarily mean the Middle Man class or this particular object should be deleted: only that the Client should reference the Delegate directly with a field, and not passing through a getter or a set of calls to Middle Man. In turn, the Middle Man may only be simplified by deleting the methods not called anymore.

The Server should be actually removed when there are no more calls from the Clients; but it's no issue if the Clients gains now both the Server and the Delegate as collaborators.

Steps

  1. Create a getter for the Delegate on the Server object.
  2. Substitute calls from the Clients to the Server with calls on the object returned from the getter.
  3. Inject directly the Delegate into the Clients by updating their factories or their creational code.

Run tests at the functional or end-to-end level to check for regression, updating the unit tests accordingly. An additional step is to delete the Server class if it does not currently have other responsibilities than providing access to Delegate.

Step 3 is not described by Fowler, but I'm a fan of the Misko way of separating object construction from logic, so I included it. The difficulty in the step comes when the Client and the Delegate have a different lifecycle - in particular, the Delegate must have a longer lifecycle than the Client for this refactoring to be successful. For example, it's simple to inject a database connection (object that lasts from the script's start to the end) as the Delegate into a Service Layer object (object which is created to satisfy a particular kind of request).

Example

We continue with the example of the Hide Delegate article - this time throwing away the UserCollecton Middle Man and injecting User directly in our controller.

In the initial state, UserController passes through UserCollection to get to User:

<?php
class RemoveMiddleMan extends PHPUnit_Framework_TestCase
{
    /**
     * In the previous example, we were delegating the activation logic to the
     * UserCollection, modeling only HTTP request-related concerns into our 
     * UserController.
     */
    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 hides 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);
    }
}

/**
 * The Client.
 */
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']);
    }
}

The controller can be modified to call methods on a User object:

/**
 * The Client now accesses a User object.
 */
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->getUser($request['name'])->activate($request['activationNumber']);
    }
}

And finally we can simplify the picture by injecting User in UserController and deleting UserCollection:

<?php
class RemoveMiddleMan extends PHPUnit_Framework_TestCase
{
    /**
     * The User is now directly injected (it may be found at construction time.)
     * We maintain the reference to the object in the test for verification
     * purposes; this test has become a unit test and we could even use a Mock.
     */
    public function testUserIsActivatedIfActivationTokenIsCorrect()
    {
        $controller = new UserController($user = new User('giorgio', 42));
        $controller->activation(array(
            'activationNumber' => 42
        ));
        $this->assertTrue($user->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 Client now only refers to an User object since it does not have any 
 * other use for UserCollection.
 */
class UserController
{
    private $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function activation(array $request)
    {
        if (!isset($request['activationNumber'])) {
            throw new InvalidArgumentException('No activation number.');
        }
        $this->user->activate($request['activationNumber']);
    }
}
Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)