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: Extract Subclass

Practical PHP Refactoring: Extract Subclass

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

Join the DZone community and get the full member experience.

Join For Free

So far, we have only treated the movement of object members (fields and methods, and constructor as special methods); the assumption we made was that these members are moved between classes in an hierarchy which already exist.

Larger scale refactorings involve modifying the hierarchy itself by adding and removing classes. In the scenario of today, a set of members (either methods or fields) is used only in some instances of a class. The proposed solution is to extract a subclass where those members can be moved.

What a subclass represent

You can think of classes, in mathematical terms, as precisely defined set (the ordinary, non-fuzzy one). A class represents a set of all its instances (it is actually isomorphic... let's just say it like that).

A subclass represents a subset of the original set, so only some instances of the superclass will be also instances of the subclass.

In most programming languages, subclasses of a given class are disjunct sets, but they may not cover the whole original set unless the superclass is abstract.

In any case, a characteristic that applies only to some instances indicates an unexpressed subset, and we can extract a subclass to represent it.

Moreover, all the instances not in the subset (instances of the superclass but not of the subclass) will be simplified as their code will not comprehend methods and fields which are not necessary.

Steps

  1. Define a subclass of the original one with the extends keyword.
  2. Split the original constructor if needed: the initialization of fields that are only in the subclass must be in the subclass constructor, so that they are not required to instantiate the superclass.
  3. Replace calls to the constructor, which are usually new operators but also static Factory Methods. Separating business from construction logic helps here as all your instantiations will be in creational objects like Factories and Builders.
  4. Now that all client code already refers to the right instances, use Push Down Method and Push Down Field on all the members only interesting for the subclass
  5. The tests should pass.

Since this refactoring involves modyfing the hierarchy and the client code that deals with instantiation, you should execute the whole test suite.

An additional step is suggested by Fowler: there could be some fields that represent information now carried by the hierarchy (e.g. a type code). These data can be the target of and become fixed into the hierarchy: for example you can substitute a $itemType field with a itemType() method which returns a constant string, and that is redefined in the subclass.

Example

We start from a single class, NewsFeedItem, representing an item in a list of updates shared in a social network.

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

    public function testALinkShowsItsAuthor()
    {
        $link = new NewsFeedItem("/posts/php-refactoring", "giorgiosironi");
        $this->assertEquals("<a href=\"/posts/php-refactoring\">/posts/php-refactoring</a> -- @giorgiosironi",
                            $link->toHtml());
    }
}

class NewsFeedItem
{
    protected $content;
    protected $author;

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

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

    public function toHtml()
    {
        return "<a href=\"$this->content\">$this->content</a> -- $this->author";
    }
}

We notice there are two patterns of usage, described by the tests:

  • instances representing text.
  • Instances representing a link.

Moreover, the toHtml() method is used only by those instances which model links, as text is enough for ordinary object. We can extract a subclass, Link. Let's define it:

class Link extends NewsFeedItem
{
}

We replace the instantiations in client code where needed; in this example this code is represented by the tests:

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

    public function testALinkShowsItsAuthor()
    {
        $link = new Link("/posts/php-refactoring", "giorgiosironi");
        $this->assertEquals("<a href=\"/posts/php-refactoring\">/posts/php-refactoring</a> -- @giorgiosironi",
                            $link->toHtml());
    }
}

We execute Push Down Method on toHtml(), which is only called for Link objects. There are no other members to move.

class NewsFeedItem
{
    protected $content;
    protected $author;

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

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

class Link extends NewsFeedItem
{
    public function toHtml()
    {
        return "<a href=\"$this->content\">$this->content</a> -- $this->author";
    }
}

An additional step could be to redefine the constructor to provide a more precise API, calling the first field $url or $path instead of $content.

PHP Extract

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Beginner's Guide to Infrastructure as Code
  • Cloud Performance Engineering
  • Testing Repository Adapters With Hexagonal Architecture
  • DevOps vs Agile: Which Approach Will Win the Battle for Efficiency?

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: