Building Objects

You should try to model objects on real life objects. This seems like a relatively simple idea but this week I realised that I have a few objects that know too much when they are constructed.

When an object is created I usually think about all the knowledge it will need going forward, so for example in my Tic Tac Toe game I thought a player will need to know about a board so added that into the constructor. This isn’t ideal because it links a player into a concrete implementation of the board. This works for me at the moment because I have a mutating (I always think of TMNT whenever anyone talks about mutation!) board, but when I have to introduce a immutable board I might have a problem, because my player will always have a single representation of the board when it is constructed and so if they have to decide which cells are taken, they will have an outdated board. So it is better to pass the board as a parameter to the methods that use them within the board class.

It is a relatively simple change. Here is what I had before:

public HumanPlayer(IO io, Board board, Symbol symbol) { = io;
this.board = board;
this.symbol = symbol;

and here is what I changed it to:

private int validMove(Board board) {
while (!digitInput(userInput) || !board.isPositionEmpty(indexChosen)) {
io.showOutput(“That position is already taken or is not on the board, try again.”);
return indexChosen;

So I am going to try and think about what an object really needs to know at the beginning of its life not about what it needs to know for the whole duration of the program.