Test Your Example Code!

Developers work hard to keep their skills sharp. Personally, I’ve found it incredibly rewarding to read books about software development to level up my skills, and there are a lot of great books out there. However, I’ve been noticing something extremely frustrating: many of the code examples I encounter have errors.

Sometimes it’s a small issue, but I’ve seen cases where a variable’s name will completely change from one line to the next. Errors make comprehension significantly more difficult at the worst possible time. Example code is almost always trying to convey something new or reinforce a point. When you introduce mistakes, you’re making it extra difficult for the reader to understand what you’re trying to show her. Unlike a misspelled word, the necessary correction may not be evident. Worse still, the reader may be completely unaware that an issue is present at all and instead be left confused as to why your code just doesn’t seem to make sense.

Unfortunately, this doesn’t just happen in books. Blog posts, readme files, and other documentation is often fraught with code examples that either don’t do what they’re supposed to or won’t even execute. It’s probably obvious, but it’s in your best interests to make sure all your code examples work. If the example code for your package doesn’t work, I’m more likely to move on to something else than try to figure it out. If I’m reading your book, broken examples hurts your credibility. I shouldn’t have to fix your code just to try it out!

But I’ve got good news! It’s an easy problem to fix. All you have to do is actually run your code examples to make sure they do what you think they do. I know, I know… you’re the world’s greatest developer and there’s no way you screwed up that 10-line code snippet… right?

Broken JavaScript examples are especially pathetic. Testing takes just seconds in your browser’s developer tools.

Would you ever ship code you didn’t test? No? Then why should your examples be any different? Think back on the some of the mistakes you or others have caught in your code. If you’re like me, there’s more than a few which resulted in applying your palm to your face. It happens, and that’s why we do code reviews.

It takes at most a few minutes to dump your code somewhere and run it. You owe it to your readers to do this. Make their job as easy as you can.

Here is a list of places where you can quickly test code:

  • Your browser’s developer console or a Node REPL (type node from a terminal to enter) for JavaScript
  • CodePen for HTML/CSS/JavaScript (also supports preprocessers like Pug, Sass, or CoffeeScript)
  • fiddles.io for tons of other languages

You could also set up a dedicated testing project just for copying in code to run. The point is to make it super easy so you’ll actually do it.

Alex Bainter writes code at Spreetail.