dimanche 18 février 2018

Business logic in command design pattern

I use the command design pattern to deal with player actions.

For example, below is the command that handles a dice roll.

interface ICommand
{
    public function execute(Game $game) : void;
}

class RollDiceCommand implements ICommand
{
    private $player;

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

    public function execute(Game $game) : void
    {
        $dice = DiceFacade::roll(new NumberGenerator());

        // Currently a business logic goes here

        if ($dice->isDouble()) {
            $player->incrementDoubleCount();

            if ($player->getDoubleCount() === 3) {
                $command = new GoToJailCommand();
                $command->execute();
            }
        } else {
            // The next player turn
            $game->nextPlayer();
        }

        // ...
    }
}

  1. Is it good idea to store a business logic in the command?
  2. Should I call an another command directly from the roll command or I need to avoid it? The idea of throwing an event in the command seems better to me. What do you think about it?

Thank you!

Aucun commentaire:

Enregistrer un commentaire