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 637 posts at DZone. You can read more from them at their website. View Full User Profile

Practical PHP Refactoring: Pull Up Constructor Body

01.02.2012
| 3813 views |
  • submit to reddit

After Pull Up Field and Pull Up Method, we explore today the last of this category of refactorings: Pull Up Constructor Body.

The scenario consists of a series of constructors that contain duplication, and are spreaded among a few classes having a common ancestor. The solution proposed by this refactoring is to pull up the body of the constructor, or part of it, in order to eliminate the duplication.

Why a constructor is not just a method?

This refactoring is different from Pull Up Method because it uses special semantics like calls to parent. Moreover, in some languages, constructors are not inherited; in PHP they are, so the inheritance aspect is not important.

The difference between pulling up a method and a constructor is that in the latter case there is a standard way to separate the common code (to pull up) and the specific one (to leave in the subclasses). The standard form is a parent constructor, plus an overriding constructor that calls parent::__construct(), hiding it in the process. There are alternatives to overriding, like abstract init() methods, but they do not capture all the additional special case parameters that may be needed at instantiation time.

For example, PHPUnit uses this variation with setUp() methods, which are called by the parent class and handle customization of a test. However, you can't pass anything from the outside as setUp() must take no arguments. This isn't a problem in that specific case because you'll never instantiate test cases by yourself, but in general you will instantiate a lot of objects and so the subclasses constructor should be free to require additional arguments.

In fact, overriding constructors is a special operation, as you can redefine all the parameters and their number or order, add or drop type hints, and specify default values. You can't do that with ordinary methods:

PHP Fatal error:  Declaration of Subclass::method() must be compatible with that of Superclass::method() in ...

As in all the Pull Up refactorings, thanks to inheritance the client code does not have to change.

Steps

Note that the code to pull up should be moved at the beginning of the constructors. Usually a constructor is a set of independent instructions so there will be no problem; if you're separating construction and business logic you won't have difficulties.

  1. Define a constructor in the superclass (initially empty and not called).
  2. Move the common code, which should be at the beginning of the constructor, up in the superclass.
  3. Call the superclass constructor as the first step of each subclass constructor.

It is a C++ convention to keep the call to the parent constructor as the first step (in C++, by default the call is performed automatically.) Destructors, which are rarely used, have opposite semantics.

Example

We restart from the end of the previous refactoring, but a change in requirements has made the duplication on the author field initialization more evident. This is just standard code for ensuring a @ is placed in front of author names:

<?php
class PullUpConstructorBody extends PHPUnit_Framework_TestCase
{
    public function testAPostShowsItsAuthor()
    {
        $post = new Post("Hello, world!", "giorgiosironi");
        $this->assertEquals("Hello, world! -- @giorgiosironi",
                            $post->__toString());
    }

    public function testALinkShowsItsAuthor()
    {
        $link = new Link("http://en.wikipedia.com", "giorgiosironi");
        $this->assertEquals("<a href=\"http://en.wikipedia.com\">http://en.wikipedia.com</a> -- @giorgiosironi",
                            $link->__toString());
    }
}

abstract class NewsFeedItem
{
    /**
     * @var string  references the author's Twitter username
     */
    protected $author;

    /**
     * @return string   an HTML printable version
     */
    public function __toString()
    {
        return $this->displayedText() . " -- $this->author";
    }

    /**
     * @return string
     */
    protected abstract function displayedText();
}

class Post extends NewsFeedItem
{
    private $text;

    public function __construct($text, $author)
    {
        $this->text = $text;
        $this->author = '@' . ltrim($author, '@');
    }

    protected function displayedText()
    {
        return $this->text;
    }
}

class Link extends NewsFeedItem
{
    private $url;

    public function __construct($url, $author)
    {
        $this->url = $url;
        $this->author = '@' . ltrim($author, '@');
    }

    protected function displayedText()
    {
        return "<a href=\"$this->url\">$this->url</a>";
    }
}

We define a constructor, which for now is overridden and invisible:

abstract class NewsFeedItem
{
    /**
     * @var string  references the author's Twitter username
     */
    protected $author;

    public function __construct()
    {
    }

    /**
     * @return string   an HTML printable version
     */
    public function __toString()
    {
        return $this->displayedText() . " -- $this->author";
    }

    /**
     * @return string
     */
    protected abstract function displayedText();
}

We move the common code inside the superclass constructor. The tests are failing now:

abstract class NewsFeedItem
{
    /**
     * @var string  references the author's Twitter username
     */
    protected $author;

    public function __construct($author)
    {
        $this->author = '@' . ltrim($author, '@');
    }

    /**
     * @return string   an HTML printable version
     */
    public function __toString()
    {
        return $this->displayedText() . " -- $this->author";
    }

    /**
     * @return string
     */
    protected abstract function displayedText();
}

class Post extends NewsFeedItem
{
    private $text;

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

    protected function displayedText()
    {
        return $this->text;
    }
}

class Link extends NewsFeedItem
{
    private $url;

    public function __construct($url, $author)
    {
        $this->url = $url;
    }

    protected function displayedText()
    {
        return "<a href=\"$this->url\">$this->url</a>";
    }
}

To make the test pass again, we have to call the parent constructor:

class Post extends NewsFeedItem
{
    private $text;

    public function __construct($text, $author)
    {
        parent::__construct($author);
        $this->text = $text;
    }

    protected function displayedText()
    {
        return $this->text;
    }
}

class Link extends NewsFeedItem
{
    private $url;

    public function __construct($url, $author)
    {
        parent::__construct($author);
        $this->url = $url;
    }

    protected function displayedText()
    {
        return "<a href=\"$this->url\">$this->url</a>";
    }
}

The refactoring has eliminated any source of duplication in this class. There are possible follow-ups to this refactoring:

  • the parent constructor could become protected since the class is abstract and cannot be instantiated anyway.
  • The parameters of the subclasses constructors could be reordered to be consistent with the superclass, putting $author first. But that would require to modify client code, and it's out of the scope of this refactoring.
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.)