Thursday, June 19, 2014

Programming Adventure

So I spent a lot of time revising and debugging the level 5 Athens paths this week, and along the way I ran into a particularly nasty save-load bug. It was kind of an adventure to track down as well as a reminder about why good programming techniques were important, so I thought it'd be fun to write a post about.

The hunt began when I noticed the story map complaining about how it couldn't find the node corresponding to a certain location in the story. This error happens on occasion as we're adding new content piecemeal. It's usually harmless, but I wanted to clean things up in preparation for an eventual alpha test, so I decided to look into it.

What I found next was mysterious, the reason the map UI couldn't find an appropriate node was because the name it was being passed was blank. Further investigation revealed this error only happened when I loaded a particular save game...

An important step to solving most bugs is to get a reproducible case, so I set to work trying different approaches until I discovered that loading the same game twice would trigger warnings on the second load (but not the first).

Baffled, I went to examine the loading code, which looked fine. However, there was one comment warning me that the code would behave in a non-obvious way under certain conditions... exactly the conditions I was seeing the bug in. Sure enough, when I inspected that code more clearly I found a variable that wasn't properly reset on load, causing weird zombie paths that had the blank location names which were causing the initial error (and probably lots of other errors too).

So some take home lessons if you’re an aspiring programmer.
1. Make your code assert if anything strange is going on, even if the code could handle it. Weird values are a good indicator something is going wrong somewhere else.

2. Get a reproducible case. It's especially good if you can get one with only a few steps.

3. If you want to do something that's clever but a little bit confusing in code, make sure you leave a comment explaining what's going on. When a frustrated programmer (possibly even yourself) stumbles on that code at 2 in the morning trying to hunt down some obscure bug, you want her to be able to figure out what’s going on without having to solve some programming riddle.

No comments:

Post a Comment