vendredi 8 mai 2015

Which approach is better? Object variables, or passing them to methods? And testing?

Here are two classes. Those classes do the same: extracts scores, teams and players from a log file, and calculate something (fictional).

First case, no variables at all, this version is easier to test, but horrible to maintain:

class TestMe1
{
    private function getPlayers ($source)
    {
        // get players from $source and return
    }

    private function getTeams ($source)
    {
        // get teams from $source and return
    }

    private function calcScores ($source, $players, $teams)
    {
        return array($source * $players * $team);
    }

    public function process ($source)
    {
        $players = $this->getPlayers ($source);
        $this->getTeams ($source, $players);
        return $this->calcScores($source, $players, $teams);        
    }
}

the second is way better to maintain:

class TestMe2
{
    private $source, $players, $teams;

    private function getPlayers()
    {
        $this->players = '';
        // get players from $source
    }

    private function getTeams()
    {
        $this->teams = '';
        // get teams from $source
    }

    private function calcScores()
    {
        return array($this->source * $this->players * $this->teams);
    }

    public function process ($source)
    {
        $this->source = $source;
        $this->getPlayers();
        $this->getTeams();
        return $this->calcScores();        
    }
}

here I "internally" store the variables, so no need to pass them. But harder to test. If I want to test calcScores() I need to create such fixture which is in exactly format what it expects. It doesnt sounds OK for me

Aucun commentaire:

Enregistrer un commentaire