Agile Zone is brought to you in partnership with:

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

Practical PHP Refactoring: Inline Class

07.28.2011
| 5744 views |
  • submit to reddit

Every refactoring technique is potentially bidirectional: their list is a toolbox, and you decide when to use each tool.

Inline Class is the inverse of Extract Class: when a class does not justify its existence and it has become a useless indirection, you can inline its responsibilities in the class(es) using it.

If extraction removes duplication, doesn't inlinine lead to duplication?

As always, let's pose the why question. A typical reason for inlining is the removal of responsibilities from the requirements, or the movement of them elsewhere. For example, you may find out that formatting dates in a localized format is a responsibility left to the client side; or that is not required at all, being the application's target all computer scientist.

The rules of simple design tell us when inlining becomes important, too. According to the rules, our work is finished when the design:

  1. Runs all the tests.
  2. Expresses every idea that we need to express.
  3. Says everything once and only once..
  4. Has no superfluous parts.

Once we lose or modify a test (changed requirements), or do not need to express an idea anymore (unuseful abstraction), or do not feel duplication (there is only one composer for this class), then the 4th rule prevails. It's not true that you should go on extracting methods and classes up until each one of them is 2-line long: eliminate the superfluos moving parts, since they're additional complexity.

Steps

  1. Duplicate all public method signatures of the class to remove into the absorbing one (Fowler's nomenclature). These methods should just delegate to the original class for now. The methods can be declared as private if this is the only class to use the original one.
  2. Change references from $this->collaborator->method() to $this->method().
  3. Apply Move Method and Move Field to put the meat in these methods.
  4. Remove the original class: at this time it should be an empty shell.

Example

We start from a situation similar to the ending of the Extract Class example. This time, the requirement for complex formatting has been removed, and little responsibility is left to MoneyAmount. The inlined class is taking up many lines of code to perform just a concatenation.

<?php
class ExtractClassTest extends PHPUnit_Framework_TestCase
{
    public function testDisplaysMoneyInAHumanFormat()
    {
        // using strings for representation to avoid loss of precision
        $moneyAmount = new MoneySpan(new MoneyAmount('100'));
        $this->assertEquals('<span class="money">100.00</span>', $moneyAmount->toHtml());
    }
}

class MoneySpan
{
    /**
     * @param int $amount
     */
    public function __construct(MoneyAmount $amount)
    {
        $this->amount = $amount;
    }

    public function toHtml()
    {
        $html = '<span class="money">' . $this->amount->format() . '</span>';
        return $html;
    }
}

class MoneyAmount
{
    private $amount;

    public function __construct($amount)
    {
        $this->amount = $amount;
    }

    public function format()
    {
        return $this->amount . '.00';
    }
}

After the refactoring, we have fewer classes (1 instead of 2) and consequently fewer methods to maintain. The test has changed in the setup phase.

<?php
class ExtractClassTest extends PHPUnit_Framework_TestCase
{
    public function testDisplaysMoneyInAHumanFormat()
    {
        // using strings for representation to avoid loss of precision
        $moneyAmount = new MoneySpan('100');
        $this->assertEquals('<span class="money">100.00</span>', $moneyAmount->toHtml());
    }
}

class MoneySpan
{
    /**
     * @param int|string $amount
     * The constructor now takes the arguments of the inline class, too.
     */
    public function __construct($amount)
    {
        $this->amount = $amount;
    }

    /**
     * This method must not refer to the collaborator anymore,
     * but to the imported methods.
     */
    public function toHtml()
    {
        $html = '<span class="money">' . $this->format() . '</span>';
        return $html;
    }

    /**
     * The public format() method of the inline class has been included as
     * a private method. We could go on and inline this method in toHtml()
     * as well.
     */
    private function format()
    {
        return $this->amount . '.00';
    }
} 
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.)