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

Recently I have been working on the refactoring of one method when I realized how much I have skilled up as a developer in the last few years. Here is a function creating text snippet describing how to get from airport to city which I wrote approximatly 3 years ago. Immidiatelly I knew how can it be rewriten to more concise form.

public static function howToGetFromCityToAirport(string $airportCode, string $language): string
    {
        $title = '';
        $paragraph = '';
        if($language == 'en') {
            $title = '<h2&gt;How to get on the airport?</h2&gt;';
            $paragraph = self::cityToAirport($language, $airportCode);
            if (empty($paragraph))
            {
                return '';
            }
        }
        if($language == 'cz') {
            $title = '<h2&gt;Jak se dostat na letiště?</h2&gt;';
            $paragraph = self::cityToAirport($language, $airportCode);
            if (empty($paragraph))
            {
                return '';
            }
        }
        if($language == 'sk') {
            $title = '<h2&gt;Ako sa dostať na letisko?</h2&gt;';
            $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&gt;" . self::fromCityToAirport_getTitle($language) . "</h2&gt;" . $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 really faster. But it is definitely 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.