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: Collapse Hierarchy

Practical PHP Refactoring: Collapse Hierarchy

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

Join the DZone community and get the full member experience.

Join For Free

In the scenario of today, a subclass and superclass are not very different: the evolution of the code has brought them to this situation. Behavior has been removed, or moved elsewhere in the system, and they are almost the same entity.

The Collapse Hierarchy refactoring provides a series of steps to unify two such classes into one, simplifying the design.

Why removing a class?

A design that has fewer moving parts is simpler to understand and a little harder to break. An additional entity that is not representing a concept of the domain, nor providing value by eliminating duplication, is just adding accidental complexity to the design.

Keeping a hierarchy to as fewer levels as possible is also beneficial as it avoids you going up and down the hierarchy to find where a called method is defined. Even when it produces a long class, it can be a step to exit from the local minimum: form a unique class that can be broken into little pieces with composition.

The assumption of this refactoring is that there are no other subclasses in the hierarchy; if there are, they should now extend the unified class, but you should look for possible violations of the Liskov Substitution Principle. For example in the transportation domain, it's not correct to collapse a Vehicle class into its subclass Coach while making the sibling class Car extend Coach as a result.

Steps

  1. Choose which class to remove: the subclass or the superclass.
  2. Use down refactorings until one of the classes is empty.
  3. All references (mostly instantiations, but also type hints and docblocks), should now refer to the class that you're keeping.
  4. Remove the empty class, which by now is only dead code.

Between steps 2 and 3 the tests may fail; execute them in short iterations to ensure you are always in a working state. Neither pulling everything up nor pushing everything down are general solution to keep the tests green: there are counterexamples for both cases of references that break, such as the instantiation of the superclass, or a type hint for the subclass.

Example

In the example, we work with the familiar class NewsFeedItem and its subclass Link. The requirements remained for them are few, and there are no other subclasses involved; there is actually no need for NewsFeedItem by itself, and it could just as well be abstract.

<?php
class CollapseHierarchy extends PHPUnit_Framework_TestCase
{
    public function testALinkShowsItsAuthor()
    {
        $link = new Link("/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";
    }
}

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

We choose to remove the superclass. We push everything down, but we must look for references like new NewsFeedItem(...) to fix before accomplishing this step.

class NewsFeedItem
{
}

class Link extends 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";
    }
}

Now we can remove the superclass altogether, along with the extends keyword on Link.

class Link
{
    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";
    }
}
PHP

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Test Execution Tutorial: A Comprehensive Guide With Examples and Best Practices
  • DeveloperWeek 2023: The Enterprise Community Sharing Security Best Practices
  • The Beauty of Java Optional and Either
  • An End-to-End Guide to Vue.js Testing

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: