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

Practical PHP Refactoring: Rename Method

11.02.2011
| 4023 views |
  • submit to reddit

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;
    }
}
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.)