Design tic-tac-toe
easy 70 minModel a game everybody knows: marks on a grid, turns, a full line wins.
Watch lesson4:32
Entities
Four classes, and why a cell is not one of them
The point: a class needs state of its own and a decision of its own. Most nouns of this game have neither.
Keep
What earns its place
| Type | State | Decision |
|---|---|---|
Game | Turn, status, moves | May this move be made now? |
Board | Squares, number of empty ones | Is this square free? |
LineCounts | Counters | Did this move complete a line? |
Move | Row, column, mark | None: a record |
Mark, Status | Values | other |
Reject
What does not
| Noun | Why not | Say |
|---|---|---|
| Cell | Its row and column are its place in the list. Its mark is the value there | "A value, not an object." |
| Player | A name and a mark. Nobody asks it anything yet | "It becomes an interface when it can choose." |
| Row, Column, Diagonal | A number each, in one map | "Keys, not classes." |
| GameManager, Controller | There is one game | "When there are many, it is a hall with tables." |
| WinnerStrategy with five subclasses | One rule is known | "LineCounts can be handed in when there is a second." |
| Screen, Printer | Output | "They use rows()." |
Where does the win check live?
BreaksIn the screen or in main
- How
- After each move, main looks at the board.
- Limit
- Two screens have two win checks. A test of the rules needs a screen.
- Choose when
- Never.
WorksIn Board, as winner()
- How
- The board reads its own lines.
- Limit
- The board now has two reasons to change: storage and rules. It cannot be used for a game with other rules.
- Choose when
- Small boards and no undo. Many good answers do this.
StrongIn an object that sees each move
- How
LineCounts.add(move)answers for this move only.- Limit
- It must see all moves and all undos. The game guarantees that, because it is the only caller.
- Choose when
- Any size, undo, or more than one rule.
Design it twice
The smallest design that could work
One class Game with a list of nine letters and a method play, about forty lines. For 3 by 3 without undo it is the better design, and it is fair to say so. Each split on this page is paid for by a sentence from the requirements: any size pays for LineCounts, undo pays for Move, and both together pay for Board.