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

Practical PHP Refactoring: Replace Type Code with Class

Giorgio Sironi user avatar by
Giorgio Sironi
·
Sep. 21, 11 · Interview
Like (0)
Save
Tweet
Share
9.04K Views

Join the DZone community and get the full member experience.

Join For Free

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');
    }
}
PHP

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • OWASP Kubernetes Top 10
  • Java Code Review Solution
  • Secure APIs: Best Practices and Measures
  • 5 Software Developer Competencies: How To Recognize a Good Programmer

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: