Say I am developing a very simple card game. The card game has two phases.
1st Phase: Everone draws a card in turn order. 2nd Phase: Everyone plays a card, in turn order.
So, I model the game with an api that looks like this:
public class Game {
public void draw(PlayerId playerId) {
Player player = players.get(playerId);
player.drawFrom(drawDeck);
}
public void play(PlayerId playerId, CardId cardId) {
Player player = players.get(playerId);
player.playCard(cardId);
}
}
Here is my problem: the Game class has two methods to call, but only one method is valid at any one particular time. If the game is in the first phase, then the method play
shouldn't be called. Likewise, if the game is in the second phase, the method draw
should not be called.
What options do I have in this situation? I can only think of throwing exceptions if methods are called when they shouldn't be.
Ideally, I would like the client code to only be able to call the methods that are valid at that particular time. Any ideas on how I can do this? Or should the onus be on the client to call the methods correctly?
Aucun commentaire:
Enregistrer un commentaire