Tuesday, October 21, 2008

Don't Make Me Think (About Code)

I'm a stickler for clean, easy to read code. In fact, I'll take clean, incomplete code over working, unreadable code. It's alot easier to finish and maintain clean code than to clean up spaghetti code. One of the best compliments I've ever received in my career was from a coworker who told me that my code was a pleasure to read. While cleaning up some old Java code at work, I came across this line in a random number generator: seed += lastSeed++; I had do a double-take on that line. It's short but ugly and easily confusing. Does lastSeed increment before being added to seed or after? I even checked with a coworker and he wasn't totally sure the order of operations here. (Yes, lastSeed gets incremented *after* being added to seed. I even ran some test code to confirm it.) I'm pretty sure I had questions like these on my college C programming exams. I once read a book about web usability titled Don't Make Me Think by Steve Krug. The point of the book isn't that web sites should be dumbed down to be usable, but that their structure should flow naturally. A user shouldn't have to stop and decipher confusing or ambiguous links. Eg: Do I click "About Us" or "Support" to find a company's mailing address? Likewise, an important aspect of clean code is that it should be obvious how it works. It shouldn't rely on obscure language features or shortcuts. You shouldn't have to stop and ask yourself "Wait, what is this doing?" In the end, I made a simple change to the code: seed += lastSeed; lastSeed++; Yes, I added an extra line of code, but I removed any possible confusion about the order of operations. Sure, it's a simple example, but imagine if this code was being used for financial calculations. It would be way to easy to introduce a bug when it was being done all in one line. Cleaning up these things isn't just a matter of making things safer for junior level programmers (as the Java Ranch Style Guide reasons) - even the most experienced programmers make dumb mistakes. Straightforward code makes life easier for everyone.

No comments: