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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Extract Tables from PDFs and Other Documents in C#
  • AI Is Making PHP Cool Again
  • Kotlin Code Style: Best Practices for Former Java Developers
  • Beyond Extensions: Architectural Deep-Dives into File Upload Security

Trending

  • Stop Paying a Model to Make Decisions You Already Made
  • How You Clear Your HTML5 Canvas Matters
  • Event-Driven AI Systems With Kafka and Autonomous Agents
  • Agentic Systems and Design Patterns

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Practical PHP Refactoring: Extract Method

Practical PHP Refactoring: Extract Method

By 
Giorgio Sironi
·
Jun. 13, 11 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
2.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

I'm starting a new series: Practical PHP Refactoring. Each article will cover one of the refactorings defined by Fowler in its classic book, applied to PHP code.

Extract Method means creating a new method to contain part of the existing code: it's one of the most basic refactoring that you should be able to perform, just like every chef is able to chop vegetables or to turn on the gas. It's a building block to more complex refactorings.

Many, many issues derive from methods that are (or have become) too long, or that confuse different concepts in the same block of code.

Why should I extract a method?

Extract Method is one of the simplest tool to help encapsulation. It brings a simplification of the scope, since all variables defined inside the method won't be able to pollute the calling code. The refactoring is called Extract Method since it's about object-oriented programming, but Extract Function would have the same meaning.

Extract Method forces you to define a contract with a piece of code, comprehending the inputs (method parameters) and the outputs (a return value). It's not real Design by Contract, but it fits the 80% of the cases.

Finally, an extracted method may be reuses independently from the calling code. Eliminating duplication is one of the driving forces that makes most of refactoring techniques interesting.

Steps

I follow Fowler's recipes, but I will customize it to my style of development (since I write the code samples) and to PHP peculiarities.

1. Create the method, and choose a meaningful name. Thirty seconds spent here can avoid renaming a doSomething() method in thousands of different calls in the future.

A good option may be trying to call it from the point where you want to extract it from, to establish a signature handy for the client (like for TDD). But atferwards, comment the call again, since these steps must not break anything. We should go from a green state to another green state.

2. Copy the extracted code into to the new method. Scan it and fix variable references:

  • variables existing prior to the call become the method parameters.
  • Variables that are created in the block of code, and used afterwards, are part of the return value. Typically this is only one variable, but if there is more than one you can wrap them in an object or (temporarily) in an associative array.
  • Local variables may now be hidden inside the method: they are not referenced outside the code and PHP will garbage-collect them when the method finishes (if they are not referenced anymore, of course).

3. Replace original code with a call to the method.

4. Perform renamings or refactorings inside the extracted method.

Example

The code sample shows you the various steps applied to running PHP code. I also provide a test, since I already use it to check the refactoring has gone well.

We start from a method that mixes regular expressions with date formatting:

<?php
class ExtractMethodTest extends PHPUnit_Framework_TestCase
{
    public function testMethodExtractionShouldNotMakeThisTestFail()
    {
        $logParser = new LogParser();
        $logLine = '127.0.0.1 - - [04/30/2011:17:07:31 +0200] "GET /favicon.ico HTTP/1.1" 404 450 "-" "Mozilla"';
        $day = $logParser->getDayOfTheWeek($logLine);
        $this->assertEquals('On Saturday we got a visit', $day);
    }
}

class LogParser
{
    public function getDayOfTheWeek($logLine)
    {
        preg_match('([0-9]{2}/[0-9]{2}/[0-9]{4})', $logLine, $matches);
        $extractedDate = $matches[0];
        $date = new DateTime($extractedDate);
        return 'On ' . $date->format('l') . ' we got a visit';
    }
}

We extract a method, and in the TDD style we do just as much as it takes to keep a green test. We call this method from the old code immediately: this is the bigger step.

<?php
class ExtractMethodTest extends PHPUnit_Framework_TestCase
{
    public function testMethodExtractionShouldNotMakeThisTestFail()
    {
        $logParser = new LogParser();
        $logLine = '127.0.0.1 - - [04/30/2011:17:07:31 +0200] "GET /favicon.ico HTTP/1.1" 404 450 "-" "Mozilla"';
        $day = $logParser->getDayOfTheWeek($logLine);
        $this->assertEquals('On Saturday we got a visit', $day);
    }
}

class LogParser
{
    public function getDayOfTheWeek($logLine)
    {
        $date = $this->getDate($logLine);
        return 'On ' . $date->format('l') . ' we got a visit';
    }

    function getDate($logLine)
    {
        preg_match('([0-9]{2}/[0-9]{2}/[0-9]{4})', $logLine, $matches);
        $extractedDate = $matches[0];
        $date = new DateTime($extractedDate);
        return $date;
    }
}

Finally, we refine the extracted method, deciding its scope, adding a docblock and eliminating temporary, explanatory variables now rendered useless by the simplicity of this method.

<?php
class ExtractMethodTest extends PHPUnit_Framework_TestCase
{
    public function testMethodExtractionShouldNotMakeThisTestFail()
    {
        $logParser = new LogParser();
        $logLine = '127.0.0.1 - - [04/30/2011:17:07:31 +0200] "GET /favicon.ico HTTP/1.1" 404 450 "-" "Mozilla"';
        $day = $logParser->getDayOfTheWeek($logLine);
        $this->assertEquals('On Saturday we got a visit', $day);
    }
}

class LogParser
{
    public function getDayOfTheWeek($logLine)
    {
        $date = $this->getDate($logLine);
        return 'On ' . $date->format('l') . ' we got a visit';
    }

    /**
     * @return DateTime
     */
    private function getDate($logLine)
    {
        preg_match('([0-9]{2}/[0-9]{2}/[0-9]{4})', $logLine, $matches);
        return new DateTime($matches[0]);
    }
}
PHP Extract code style

Opinions expressed by DZone contributors are their own.

Related

  • How to Extract Tables from PDFs and Other Documents in C#
  • AI Is Making PHP Cool Again
  • Kotlin Code Style: Best Practices for Former Java Developers
  • Beyond Extensions: Architectural Deep-Dives into File Upload Security

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook