Small ideas – quick refactoring of legacy code after couple of years

I have recently been working on a refactoring of a method when I realized how much I have skilled up as a developer in the last few years.

Here is a function creating a text snippet describing how to get from the airport to the city, which I wrote approximately three years ago. Immediately I knew how it could be rewritten to a more concise form.

public static function howToGetFromCityToAirport(string $airportCode, string $language): string
{
    $title = '';
    $paragraph = '';
    if ($language == 'en') {
        $title = '<h2>How to get on the airport?</h2>';
        $paragraph = self::cityToAirport($language, $airportCode);
        if (empty($paragraph))
        {
            return '';
        }
    }
    if ($language == 'cz') {
        $title = '<h2>Jak se dostat na letiště?</h2>';
        $paragraph = self::cityToAirport($language, $airportCode);
        if (empty($paragraph))
        {
            return '';
        }
    }
    if ($language == 'sk') {
        $title = '<h2>Ako sa dostať na letisko?</h2>';
        $paragraph = self::cityToAirport($language, $airportCode);
        if (empty($paragraph))
        {
            return '';
        }
    }
    return $title . $paragraph;
}

So what I did? I made only few changes:

  • First I extracted the common part and pushed it to $paragraph variable.
  • Then over ternary decision decided what to return.
  • If a $paragraph is not zero length then call custom private translation method and build a simple HTML string.
  • And lastly, I just simplified naming or enforced PHP type safety.
public static function fromCityToAirport(string $airportCode, string $language): string
{
    $paragraph = self::cityToAirport($language, $airportCode);
    return strlen($paragraph) == 0 ? '' : "<h2>" . self::fromCityToAirport_getTitle($language) . "</h2>" . $paragraph;
}

private static function fromCityToAirport_getTitle(string $language): string
{
    switch ($language) {
        case 'en':
            return 'How to get on the airport?';
            break;
        case 'cz':
            return 'Jak se dostat na letiště?';
            break;
        case 'sk':
            return 'Ako sa dostať na letisko?';
            break;
    }
}

The result is quite significant. 30 lines of code decreased to 20. Code is not faster. But it is more readable and divided into more cohesive parts reflecting better domain language.

This entry was posted in Refactoring and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.