I'm working on a small project in which I'm attempting to practice relatively strict adherence to two ideas:
- Tell, don't ask (TDA)
- Immutability
The main concept in this project is a Map
(as in a geographical map, not the data structure), which holds a 2D array of Tile
s. The tiles can be thought of like squares on a chessboard, with their position in the array being their position on the board.
One operation that can be performed is a line segment can be drawn, starting at one tile, and passing through one or more other tiles, before ending when it hits the edge of the map or another line already containing a tile. Drawing a line through a Tile
in this case essentially just means marking the Tile
with a boolean property saying that it contains a line.
To maintain immutability, a Tile
does not mutate its state when a line is drawn through it, instead returning a new Tile
with the line drawn. The entry point for drawing a line is a method on the map itself, which looks like:
public Map DrawLine(Tile from, Direction direction)
So the problem here is how to draw a line while adhering to the two ideas I mentioned before?
One way to draw the line, maintaining immutability but forgetting TDA, is for the Map
to take charge of the whole drawing process, working out which tiles need to be marked as containing a line, and doing that update for each one, replacing them with the newly created Tiles
in its array.
Another way, maintaining TDA but forgetting immutability, is for the Map
to tell the Tile
to draw a line, and in which direction, and then for each tile to notify the next one, until one decides that the line has to end (for example because it already contains a line). In this case, I don't see any simple way to make sure that all of the updated Tile
s are replaced in the Map
, which is why I say that this approach sacrifices immutability. The Map
itself is also supposed to be immutable, so even passing itself to the Tiles
with some kind of void UdpateTile(int x, int y, Tile replacement)
callback method wouldn't work.
So my question is: are there any techniques or patterns which would allow me to do the above, adhering to both TDA and immutability? Or, are there any more appropriate high-level designs which would allow me to tackle these requirements while also adhering to both principles? I understand that the TDA violation in this case is relatively small, so on a practical level it wouldn't be a huge sacrifice. I'm just interested in better alternatives that I may be missing.