Whenever you write code samples for an API or library – or even a blog post – you should treat it as though you are writing the production guidance system for the space shuttle. Okay, that may be a little extreme, but you should at least make your best effort to ensure the code is error free and follows best practices. Why? Any bugs, vulnerabilities, anti-patterns, or cruft of any kind will replicate like drunken bunnies.
In a blog post titled Why Windows 8 drivers are buggy Andrey Karpov discusses what he found when performing static analysis on Windows 8 driver examples published by Microsoft. In short, those examples aren’t exactly stellar. But they’re just examples and aren’t that important, right? I beg to differ.
In my opinion, the salient point of the article is best summarized in the following paragraph (emphasis mine):
Bugs in samples are not that critical as bugs in real-life software.Nevertheless, bugs can migrate from samples to real-life projects and cause developers a lot of troubles. Even within the Windows 8 Driver Samples pack we found identical bugs. The reason is obvious: copying-and-pasting a code fragment from a nearby sample. In the same way these errors will get into real-life drivers.”
In fact, I would rearrange that first sentence to read: “Bugs in samples will become critical bugs in real-life software.”
The evils of copying-and-pasting aside, the truth is that developers reading your sample code will likely (perhaps blindly) trust that a given example is the right way to do things. Like it or not, when writing examples you are acting as a teacher and can’t make any assumptions about your pupils.
To illustrate how sample code can proliferate, consider this commit to the storm-starter project. That was from two years ago, shortly after storm had been open-sourced. The impetus was to help people more familiar with java/Maven than clojure/Leiningen get started with storm. Since then, that code/comment has proliferated fairly far and wide, as can be seen from a google search for “keep storm out of the jar-with-dependencies”. In retrospect, I should have used the maven shade plugin instead, since it plays better with certain frameworks like Spring. Not a big deal, but the
cat drunken bunny is out of the bag and on a love mission.
I’ll admit that I’m in no way perfect in this respect. But I strive toward that goal and believe that all serious developers should as well.
Let’s keep the drunken bunnies at bay. ;)