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: Rename Method

Practical PHP Refactoring: Rename Method

Giorgio Sironi user avatar by
Giorgio Sironi
·
Nov. 02, 11 · Interview
Like (0)
Save
Tweet
Share
6.33K Views

Join the DZone community and get the full member experience.

Join For Free

Renaming a method, without changing its signature, is a not expensive operation and can give you a great benefit while reasoning about code. Just a change from a nonsensical name to a pronounceable one improves expressivity in technical conversations with colleagues.

Especially in legacy codebases inherited from someone else, it's better to learn a new name now than to struggle with the old ones forever. As Fowler says, code is targeted to humans first, and computers second.

Why renaming?

Small methods are good, right? We can extract and extract code until they become no longer than a few lines.

The issue, however, is that if we do not name carefully the extracted methods, we will find difficult to follow the chain of calls. Just extracting code is no good if the result is a chain of generic calls like process()->forward()->compute()->makeSomething().

A lack of a meaningful name may also point out a problem in factoring, like a useless abstraction, or one that mixes up many different concerns. Fowler's rule of thumb suggests to transform the docblock comment for the method into the method's name itself; is this results in a 160-character method name, you should perform some extractions. Apart from claring cases, length is not a problem today, especially if methods have a small scope like the many private ones that you can extract inside a class.

It's difficult to immediately get the right name for a method. Some solutions for this problem are to write first the call (in test or other code) and than the method itself; or to avoid generic verbs like process(). However, a simple strategy is to start with a good enough name and adopt a renaming before publishing your Api. As long as you have control  over all your code and integrate frequently, renaming it's not an expensive operation.

Steps

  1. Check superclasses and subclasses: in case the method is present in more than one point of the hierarchy, it should be changed everywhere.
  2. Declare a new method with new name by duplicating the original one.
  3. Make the old method call the new one to remove duplication.

Now you can change calls from the old to the new name one at the time. This is an example of parallel designs as described by Kent Beck in Responsive design talk.

When you have finished, remove the old method, or temporarily insert an exception at its start to see if it is still called somewhere. Only a good test suite can help here - PHP's dynamicity means there are no compile-time checks over the existence of a called method.

I  you do not use magic features like __call() or calls like $object->$method(), grep can be useful too:

grep -r 'methodName(' folder/

Use grep -rl if the list is overwhelming, to just show the list of files instead of all the occurrences.

Example

In the initial state, a UserRepository contains an unclear method, snafucatedUsers(). We'll just return a constant to simulate a complex calculation, since I'm interested in showing an example of the steps for this refactoring and nothing more that can counfound you.

<?php
class RenameMethod extends PHPUnit_Framework_TestCase
{
    public function testSimulatesClientCode()
    {
        $repository = new UserRepository();
        $this->assertEquals(0, $repository->snafucatedUsers());
    }
}

class UserRepository
{
    public function snafucatedUsers()
    {
        // ...complex calculations...
        return 0;
    }
}
We create the new method. There are no superclasses or subclasses to check. We just copy the other method and paste it while correcting the name.
class UserRepository
{
    public function snafucatedUsers()
    {
        // ...complex calculations...
        return 0;
    }

    public function numberOfUsersWithoutAPublicProfile()
    {
        // ...complex calculations...
        return 0;
    }
}
We make the older method delegate to the new one.
class UserRepository
{
    public function snafucatedUsers()
    {
        return $this->numberOfUsersWithoutAPublicProfile();
    }

    public function numberOfUsersWithoutAPublicProfile()
    {
        // ...complex calculations...
        return 0;
    }
}
We can change the various calls now. The test simulates all the client code we'll need to check. We can do it one call at the time, whilerunning the tests after each step.
<?php
class RenameMethod extends PHPUnit_Framework_TestCase
{
    public function testSimulatesClientCode()
    {
        $repository = new UserRepository();
        $this->assertEquals(0, $repository->numberOfUsersWithoutAPublicProfile());
    }
}

class UserRepository
{
    public function snafucatedUsers()
    {
        return $this->numberOfUsersWithoutAPublicProfile();
    }

    public function numberOfUsersWithoutAPublicProfile()
    {
        // ...complex calculations...
        return 0;
    }
}

Now we can remove the old version of the method, since grep does not found any more calls:

[14:51:29][giorgio@Galen]$ grep -r 'snafucated' .
[14:52:11][giorgio@Galen]$ 

 

The final result is:

class UserRepository
{
    public function numberOfUsersWithoutAPublicProfile()
    {
        // ...complex calculations...
        return 0;
    }
}
PHP

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Beauty of Java Optional and Either
  • What’s New in Flutter 3.7?
  • DeveloperWeek 2023: The Enterprise Community Sharing Security Best Practices
  • 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: