DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Languages
  4. Practical PHP Refactoring: Hide Delegate

Practical PHP Refactoring: Hide Delegate

Giorgio Sironi user avatar by
Giorgio Sironi
·
Jul. 27, 11 · Interview
Like (0)
Save
Tweet
Share
9.07K Views

Join the DZone community and get the full member experience.

Join For Free

The 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.

  1. 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.
  2. Adjust client calls to use the server's new method.
  3. 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.

PHP unit test Object (computer science) Test double

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Create Spider Chart With ReactJS
  • Top 5 Data Streaming Trends for 2023
  • Microservices Testing
  • Choosing the Right Framework for Your Project

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: