Programmer’s Journal: Make it a list!
In software development we often have a nose for bad code – the word used is a code smell. These can be things like duplicated code (put it in one place so it won’t take twice the effort to change it later – or even worse, only get changed in one place), or code that’s too long to figure out or understand (split it up into sections).
Lately I’ve been raising the bar for what gets my nose twitching. Basically, if I have the slightest trouble understanding my code, I see that as an opportunity to rewrite it. Yesterday I saw this with some of our dice rolling code.
We’re testing a new ability and one of the things it does is let players roll potentially an infinite number of dice:
Raining blows (mo): Every time you get a 6 when rolling for your damage score, you may automatically roll another die to add further damage. If you roll a 6 again, you may roll another die – and so on.
(Crazy, huh?) In the process of doing this, I discovered that our dice rolling code was in two entirely unconnected places:
- CombatController/requestDice: this function animates the dice and notifies the caller when it’s finished
- CombatController/showDiceAndWaitForUser: this function shows the dice popup and also responds to the dice being finished
Unfortunately now we have two pieces of code that could both respond to dice rolls finishing: requestDice and showDiceAndWaitForUser. They happen around the same time, so it’s hard to troubleshoot (we need to look in two places and we don’t know which one is working at any given time).
What it should look like
The key point I want to get across in this rambling is that it’s not enough to understand when code looks wrong – you should also have a sense in your mind of what you think it should look like. In this case, the ideal layout is a timeline:
- Show the dice popup
- Let the user start the dice rolling
- Animate the dice
- When the dice are finished, notify the caller that we’re done
The only difference between this idea and the one above is that, rather than branching into two different spots, we have one continuous line. This makes it much easier for a human being to jump in and understand what’s happening – and that’s the point of programming.
A demo!
Here’s Raining blows. There’s no sound unfortunately (a little satisfying ding plays every time you roll a 6), but it’s set up here to trigger on a 3 so it’s easier to test (and easier to pummel the Mauler):
November 26, 2013 Tuesday at 6:56 pm