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: Replace Parameter with Method

11.28.2011
| 3548 views |
  • submit to reddit

An object Client invokes a method M1, or produces a value in some equivalent way. Then, it passes the result to a new method M2 on the object Server. However, Server could look up the method by itself, due to some reference it has in its fields or via other parameters.

A simplification for this scenario is the Replace Parameter With Method refactoring: you can remove the call to M1; or, better said, you can move this call inside M2.

Actually it doesn't even need to be a call, because in the best situation Server already has access to what it needs in a field. If there is a bit of logic to apply, the parameter is effectively deleted from the signature, and obtained through a method call on Server itself or on another object.

A quick code sample showing only the mechanics of this refactoring is the following:

$partial = $object->calculate();
$serverObject->finish($partial);
// becomes
$serverObject->finish(); //internally calls $object

Assumptions

The assumption we make in order to apply the refactoring is that Server can reach M1: otherwise instead of passing the result of the operation you will have just to pass the whole object on which M1 resides (this would be an instance of Preserve Whole Object in fact.)

Why using a method call?

A method call residing in the object that needs a reference closes against new dependencies of the method M2. The reason is any change to this relationship will be encapsulated in the Server's method instead of affecting the calls to it. The result is that the client code does not need to know anymore about the parameter.
A good side effect is that this refactoring also reduces the parameter list. The method call is simple to follow and to understand.

Applying this refactoring means avoiding premature parameterization in certain scenarios: instead of making the Client object choose which reference to pass in, the Server object always reach a fixed one. If the Server does not actually need to change this reference, there's no reason to keep a parameter in place.

Thus in many cases, eliminating the parameter means preferring a simpler design now instead of preparing for tomorrow, where the requirements for the piece of code will for sure change (forcing us to introduce parameters *for other, unrelated objects*).

Steps

As a prerequisite, extract in a method the calculation of the parameter in the case it is complex. If it's just a field which is passed around or accessed, don't worry about that; but if the Server object must spend 10 lines to find the object it needs, extract that code.

(If you resort to extracting a method, a violation to the Law of Demeter is probably in place. But at least you know that the evil of deep object graph navigation is contained in that method, and you will be able to subclass it in a test or to refactor it later.)

  1. Replace references to the parameter in the method body with references to the known way for obtaining the parameter.
  2. Use Remove Parameter on the method signature, simplifying both the definition and all the calls.

The tests should pass after each step.

Example

We have an object graph consisting of a Thread and several Posts. We assume Posts are linked into a chain describing the relationship between replies and their references. For simplicity, we just display one chain at the time (although there may be more than one in the Thread state in the database.)

We are displaying the text of the various Posts with the __toString() method of the Thread. Each post also reports the previous one as a quote.

<?php
class ReplaceParameterWithMethod extends PHPUnit_Framework_TestCase
{
    public function test()
    {
        $thread = new Thread();
        $thread->add(new Post('Hello...'));
        $thread->add(new Post('Hi!'));
        $this->assertEquals("Hello...\n\n> In reply to: Hello...\nHi!\n\n", $thread->__toString());
    }
}

class Thread
{
    private $posts = array();
    private $lastPost = null;

    /**
     * Sets up a linked list of Post objects in addition to the array.
     * We assume this kind of traversal is already in place for other reasons
     * or collaborations between Post objects.
     */
    public function add(Post $post) 
    {
        $this->posts[] = $post;
        $post->setOrigin($this->lastPost);
        $this->lastPost = $post;
    }

    /**
     * This method contains mechanics that duplicate the linked list.
     */
    public function __toString()
    {
        $previousPost = null;
        $text = '';
        foreach ($this->posts as $post) {
            $text .= $post->toString($previousPost);
            $text .= "\n";
            $previousPost = $post;
        }
        return $text;
    }
}

class Post
{
    private $text;
    private $origin;

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

    public function setOrigin(Post $post = null)
    {
        $this->origin = $post;
    }

    public function toString(Post $previousPost = null) {
        if ($previousPost) {
            $text = '> In reply to: ' . $previousPost->text . "\n";
        } else {
            $text = '';
        }
        $text .= $this->text . "\n";
        return $text;
    }
}

We want each Post to use the reference to the previous post it already has. Not having done so already may seem stupid, but this code probably ended up duplicating the reference due to a previous Mikado refactoring, or because of some other change.

So we obtain the value from the field: it's really simple as the reference does not have to be navigated, and we don't need a private method.

class Post
{
    private $text;
    private $origin;

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

    public function setOrigin(Post $post = null)
    {
        $this->origin = $post;
    }

    public function toString(Post $previousPost = null) {
        if ($this->origin) {
            $text = '> In reply to: ' . $this->origin->text . "\n";
        } else {
            $text = '';
        }
        $text .= $this->text . "\n";
        return $text;
    }
}

Now we can apply Remove Parameter. The client code for once is not a test, but the Thread class. (We can also rename the method to __toString(), but it's a minor point, although it is enabled by this refactoring.)

<?php
class ReplaceParameterWithMethod extends PHPUnit_Framework_TestCase
{
    public function test()
    {
        $thread = new Thread();
        $thread->add(new Post('Hello...'));
        $thread->add(new Post('Hi!'));
        $this->assertEquals("Hello...\n\n> In reply to: Hello...\nHi!\n\n", $thread->__toString());
    }
}

class Thread
{
    private $posts = array();
    private $lastPost = null;

    /**
     * Sets up a linked list of Post objects in addition to the array.
     * We assume this kind of traversal is already in place for other reasons
     * or collaborations between Post objects.
     */
    public function add(Post $post) 
    {
        $this->posts[] = $post;
        $post->setOrigin($this->lastPost);
        $this->lastPost = $post;
    }

    /**
     * This method contains mechanics that duplicate the linked list.
     */
    public function __toString()
    {
        $previousPost = null;
        $text = '';
        foreach ($this->posts as $post) {
            $text .= $post->__toString();
            $text .= "\n";
            $previousPost = $post;
        }
        return $text;
    }
}

class Post
{
    private $text;
    private $origin;

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

    public function setOrigin(Post $post = null)
    {
        $this->origin = $post;
    }

    public function __toString() {
        if ($this->origin) {
            $text = '> In reply to: ' . $this->origin->text . "\n";
        } else {
            $text = '';
        }
        $text .= $this->text . "\n";
        return $text;
    }
}

The test still passes.

[13:42:15][giorgio@Desmond:~/Dropbox/practical-php-refactoring]$ phpunit ReplaceParameterWithMethod.php
PHPUnit 3.5.15 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 3.50Mb

OK (1 test, 1 assertion)
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.)