Chess TDD 17: Implementing Piece Movement
In this episode, I switched gears a bit to focus on the comparably easy task of moving pieces. I’d had enough of wanting to move pieces for setup, so it was time to take care of that. I also might (will at some point) revisit the test classes and perhaps consolidate to always starting with the normal board and adding/removing as needed for setup.
Here’s what I accomplished in this clip:
- Renamed that method from last time.
- Added basic implementation of move.
- Added a bit of parameter checking for move.
Here are lessons to take away:
- Simplicity isn’t just for “do the simplest thing to make it pass.” It applies on the test side as well. I started to implement MovePiece() by moving a piece two squares away, but moving it one square away is sort of a simpler case, so it’s probably better to do that first. The same kind of logic doing, say, prime factors. Start with 2 — don’t start with 2497.
- When deciding what test to write next, imagine how you might break up the work that needs to be done in terms of decomposition. When I was writing MovePiece(), I thought, “move piece means delete a piece from origin and add a piece to destination, so I’ll write a test that accounts for one of those things only: piece exists at destination.” MovePiece() may seem simple, but it’s decomposable, so let that guide your testing effort.
- If you think of a refactoring for the test method while you’re writing it, just keep writing the test. Go red then make it green, then do whatever you’re thinking in the refactor phase. Having a half-written test is no time to start refactoring.
- TDD makes you the first consumer of your API. View your API through someone else’s eyes and use that to make your code better. I discovered that I could accomplish RemovePiece(Coordinate) by calling the existing method AddPiece(null, coordinate). But that’s weird and awkward from a semantics perspective. What strikes you as awkward as you’re coding will strike your consumers as confusing, maddening, or horrifying. Don’t put them through this.