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
  1. DZone
  2. Coding
  3. Languages
  4. Practical PHP Refactoring: Replace Parameter with Method

Practical PHP Refactoring: Replace Parameter with Method

Giorgio Sironi user avatar by
Giorgio Sironi
·
Nov. 28, 11 · Interview
Like (0)
Save
Tweet
Share
5.43K Views

Join the DZone community and get the full member experience.

Join For Free

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)
PHP Object (computer science)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Introduction to Automation Testing Strategies for Microservices
  • How To Build an Effective CI/CD Pipeline
  • Use Golang for Data Processing With Amazon Kinesis and AWS Lambda
  • GitLab vs Jenkins: Which Is the Best CI/CD Tool?

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: