Search code examples
language-agnosticoopooadopen-closed-principle

OO Design, open/closed principle question


I've been thinking about this object oriented design question for a while now and have unable to come up with a satisfactory solution, so thought I'd throw it open to the crowds here for some opinions.

I have a Game class that represents a turn based board game, we can assume it's similar to Monopoly for the purposes of this question. In my design I have a Player class containing a method TakeTurn.

The Game loops through all Players and calls the TakeTurn method to do all the necessary things to complete the turn. I want to be able to have n number of players, and be able to set an arbitrary number of them to be computer players. So, my thought was to have a HumanPlayer class and a ComputerPlayer class, both of which derive from Player.

The Game knows only the Player class and simply calls the TakeTurn method on each Player in turn. My problem comes in the fact that ComputerPlayer objects can be completely automated, i.e. keeping with the Monopoly example, can decide to buy a property using some piece of logic. Now, with the HumanPlayer object, it needs to get an input from the actual user to be able to buy a property for instance, which seems to imply a different interface and potentially mean they shouldn't derive

I haven't been able to come up with a good solution to the problem without having the Game class know the actual implementations of the various Player classes explicitly. I could always make the assumption in the Game class that there will only ever be human and computer players and effectively close it for extension, but it doesn't seem like good OO programming.

Any opinions on this would be appreciated.


Solution

  • I think you should not let the Game class handle IO. this way, the (blocking) TakeTurn method will hide from the game board the means of implementation. it can use other objects to communicate with the user.

    All the Game class should concern itself with is the state of the board and the turn. the players should all implement a single Player interface, and hide all implementation from the Game.