OOP (course 3): Inheritance, Abstract Classes, Interfaces and other amazing things
Abstracting a Class into 2 Smaller Pieces
  Start your All-Access Pass to unlock this challenge
Buy Access Login

Challenge 1 / 1

Our project has this StringTransformer class:

class StringTransformer
{
    public function transformString($str)
    {
        $cacheFile = __DIR__.'/cache/'.md5($str);

        if (file_exists($cacheFile)) {
            return file_get_contents($cacheFile);
        }

        $newStr = '';
        foreach (str_split(strrev($str), 2) as $twoChars) {
            // capitalize the first of 2 characters
            $newStr .= ucfirst($twoChars);
        }

        if (!file_exists(dirname($cacheFile))) {
            mkdir(dirname($cacheFile));
        }
        file_put_contents($cacheFile, $newStr);

        return $newStr;
    }
}

But a new developer we recently hired suggests refactoring it into 2 separate classes:

class Cache
{
    public function fetchFromCache($key)
    {
        $cacheFile = $this->getCacheFilename($key);

        if (file_exists($cacheFile)) {
            return file_get_contents($cacheFile);
        }

        return false;
    }

    public function saveToCache($key, $val)
    {
        $cacheFile = $this->getCacheFilename($key);

        if (!file_exists(dirname($cacheFile))) {
            mkdir(dirname($cacheFile));
        }

        return file_put_contents($cacheFile, $val);
    }

    /**
     * Extra credit private method to avoid duplication
     */
    private function getCacheFilename($key)
    {
        return __DIR__.'/cache/'.md5($key);
    }
}

and

class StringTransformer
{
    private $cache;

    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }

    public function transformString($str)
    {
        if ($result = $this->cache->fetchFromCache($str)) {
            return $result;
        }

        $newStr = '';
        foreach (str_split(strrev($str), 2) as $twoChars) {
            // capitalize the first of 2 characters
            $newStr .= ucfirst($twoChars);
        }

        $this->cache->saveToCache($str, $newStr);

        return $newStr;
    }
}

What are the advantages of this refactoring?

Skip challenges and go to theNext Chapter

Turn Challenges Off?

All further challenges will be skipped automatically.
You can re-enable challenges at any time on this page or from your account page.