zagales / establo

Un espacio para aprovechar (o no) el tiempo siendo exentos del servicio militar.
1 stars 0 forks source link

Where should the formatting part live? #4

Closed valentinboyanov closed 4 years ago

valentinboyanov commented 4 years ago

Formatting part lives in ScoreKeeper

class ScoreKeeper
{
    private $teamA;
    private $teamB;

    public function __construct()
    {
        $this->teamA = new Team();
        $this->teamB = new Team();
    }

    ...

    public function getScore(): string
    {
        $teamA = $this->formattedScore($this->teamA->score());
        $teamB = $this->formattedScore($this->teamB->score());

        return "{$teamA}:{$teamB}";
    }

    private function formattedScore(int $score): string
    {
        return str_pad("{$score}", 3, '0', STR_PAD_LEFT);
    }
}

class Team
{
    private $score = 0;

    public function increment(): void
    {
        $this->score++;
    }

    public function score(): int
    {
        return $this->score;
    }
}

Formatting part lives in Team

class ScoreKeeper
{
    private $teamA;
    private $teamB;

    public function __construct()
    {
        $this->teamA = new Team();
        $this->teamB = new Team();
    }

    ...

    public function getScore(): string
    {
        $teamA = $this->teamA->formattedScore();
        $teamB = $this->teamB->formattedScore();

        return "{$teamA}:{$teamB}";
    }
}

class Team
{
    private $score = 0;

    public function increment(): void
    {
        $this->score++;
    }

    public function score(): int
    {
        return $this->score;
    }

    private function formattedScore(): string
    {
        return str_pad("{$score}", 3, '0', STR_PAD_LEFT);
    }
}

Formatting part lives outside ScoreKeeper and Team

class ScoreKeeper
{
    private $teamA;
    private $teamB;

    public function __construct()
    {
        $this->teamA = new Team();
        $this->teamB = new Team();
    }

    ...

    public function getScore(): string
    {
        $formatter = new ScoreFormatter(":");

        return $formatter->format($this->teamA->score(), $this->teamB->score());
    }
}

class Team
{
    private $score = 0;

    public function increment(): void
    {
        $this->score++;
    }

    public function score(): int
    {
        return $this->score;
    }
}

class ScoreFormatter
{
    private $separator;

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

    public function format(int $scoreA, int $scoreB): string
    {
        $scoreA = $this->numberAsString($scoreA);
        $scoreB = $this->numberAsString($scoreB);

        return $teamA . $this->separator . $teamB;
    }

    private function numberAsString(int $number): string
    {
        return str_pad("{$number}", 3, '0', STR_PAD_LEFT);
    }
}