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: Pull Up Constructor Body

Practical PHP Refactoring: Pull Up Constructor Body

Giorgio Sironi user avatar by
Giorgio Sironi
·
Jan. 02, 12 · Interview
Like (0)
Save
Tweet
Share
5.37K Views

Join the DZone community and get the full member experience.

Join For Free

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Understanding and Solving the AWS Lambda Cold Start Problem
  • Steel Threads Are a Technique That Will Make You a Better Engineer
  • The Power of Zero-Knowledge Proofs: Exploring the New ConsenSys zkEVM
  • Building a RESTful API With AWS Lambda and Express

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: