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: Replace Type Code with Class

09.21.2011
| 5654 views |
  • submit to reddit

The scenario of today will be familiar to many developers which have experience with ENUM database fields: it consists in a numerical or fixed string type code used to differentiate the instances of a class.

For example, some users of your site may have a U in a private string field to distinguish them as Users, while some administrator may have an S in the field (for Superuser). Or you may have a boolean field which is false for inactive users and true for active ones.

This kind of fields is a legacy of procedural code procedural code: you may have or not have code that depends on the value of that field to work. In this first article on refactoring from type codes, we'll start from the simplest situation; in this case, the behavior of the class does not depend on the type code, which is a pure data item.

Why replacing a type code (even if there's no logic attached)?

We want to replace type codes mainly to express their existence as a first-class concept, a class; and to provide type safety so that only particular values of the code can be set.

Usually, type codes are just a scalar field, which can contain any kind of value: setters often do not check that the value is actually valid. For example, a setter may allow not only U or S to be set on the user_type field, but also other strings.

By replacing such a scalar value with an instance of a class, we gain the possibility of type hinting in the setter. Moreover, we centralize the checks in the constructor or in the Factory Methods of the new class: even if the field is reused elsewhere it will still allow the same range of values.

Finally, we pave the way for moving code onto the type code class. Even if code does not depend on the value, it may be encapsulated well into the object if it is likely to change at different time with respect to the rest of the source class. In our user/superuser example, adding new user types will result only in the modification of the smaller UserType class, without touching the larger User one and checking every single line of it.

Steps

  1. Create a new class, naming it after the type code. The class should have a private field copied by the field of the original type code.
  2. Modify the source class to incorporate the new class: at this time, it should create a new object when the code is set, and extract the value from the type code when it is needed in a getter.
  3. The tests should still be passing, even the unit-level ones of the source class.
  4. In the methods of the source class that use the old code, pull an appropriate amount of logic in the new class. Getters and setters should be included in these modifications.
  5. Change the clients to use the new interface of the class, propagating the new objects outside of it.
  6. Check the state of the test suite: after having added the new interface both in the source class and in its clients, it should be green.
  7. Remove the old interface, and the declaration of the multiple values of the code.
  8. Check the test suite to see if you're finished.

Example

In the initial state, we are using N and G as type codes for Newbie and Guru. This aesthetic field will probably change with experience, as the user becomes more active on the site; but in this first article, we consider it as just a value.

<?php
class ReplaceTypeCodeWithClass extends PHPUnit_Framework_TestCase
{
    public function testAnUserCanBeANewbieOrAGuru()
    {
        $user = new User();
        $this->assertEquals(User::NEWBIE, $user->getRank());
        $user->setRank(User::GURU);
        $this->assertEquals(User::GURU, $user->getRank());
    }
}

class User
{
    const NEWBIE = 'N';
    const GURU = 'G';

    private $rank = 'N';

    public function setRank($rank)
    {
        $this->rank = $rank;
    }

    public function getRank()
    {
        return $this->rank;
    }
}

We add the Rank class, providing also Factory Methods for later usage.

class Rank
{
    private $code;

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

    public function getCode()
    {
        return $this->code;
    }

    public static function newbie()
    {
        return new self('N');
    }

    public static function guru()
    {
        return new self('G');
    }
}

We start to use Rank inside the class: the unit test, which represent the external client code, does not change and continues to pass.

<?php
class ReplaceTypeCodeWithClass extends PHPUnit_Framework_TestCase
{
    public function testAnUserCanBeANewbieOrAGuru()
    {
        $user = new User();
        $this->assertEquals(User::NEWBIE, $user->getRank());
        $user->setRank(User::GURU);
        $this->assertEquals(User::GURU, $user->getRank());
    }
}

class User
{
    const NEWBIE = 'N';
    const GURU = 'G';

    private $rank;

    public function __construct()
    {
        $this->rank = new Rank('N');
    }

    public function setRank($rank)
    {
        $this->rank = new Rank($rank);
    }

    public function getRank()
    {
        return $this->rank->getCode();
    }
}

class Rank
{
    private $code;

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

    public function getCode()
    {
        return $this->code;
    }

    public static function newbie()
    {
        return new self('N');
    }

    public static function guru()
    {
        return new self('G');
    }
}

Now we also use Rank in the public interface, retaining the old method names. We also remove the removed old codes and make the Rank constructor private. Along with the type hint in setRank(), this move prevents invalid values from being set.

<?php
class ReplaceTypeCodeWithClass extends PHPUnit_Framework_TestCase
{
    public function testAnUserCanBeANewbieOrAGuru()
    {
        $user = new User();
        $this->assertEquals(Rank::newbie(), $user->getRank());
        $user->setRank(Rank::guru());
        $this->assertEquals(Rank::guru(), $user->getRank());
    }
}

class User
{
    private $rank;

    public function __construct()
    {
        $this->rank = Rank::newbie();
    }

    public function setRank(Rank $rank)
    {
        $this->rank = $rank;
    }

    public function getRank()
    {
        return $this->rank;
    }
}

class Rank
{
    private $code;

    private function __construct($code)
    {
        $this->code = $code;
    }

    public function getCode()
    {
        return $this->code;
    }

    public static function newbie()
    {
        return new self('N');
    }

    public static function guru()
    {
        return new self('G');
    }
}
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.)