Trying to teach people the difference between “good” code and “bad” code is sometimes tricky. The science vs. art conundrum often gets in the way. One metaphor that many people turn to is that of “code smells”. The idea is that sub-par coding practices – like stale food in a refrigerator – can give off distinctive odors which software developers should become sensitive to.
But I just came across a slightly different metaphor that communicates similar principals in a different way: taste.
I was listening to an interview with Linus Torvalds (the genius behind Linux and Git) in which he elegantly demonstrated the difference between what he considers “good” taste and “bad” taste in coding. He provided a beautiful example of elegance in code. (Caveat: understanding this example requires an understanding of pointers and references, although nothing beyond a good C++ 101 class; the discussion itself can be found in this video.)
Linus provided two examples of code that do the same thing. The first one looks like this:
Now, as he explains, this is how nearly every student is taught to work with singly-linked lists. It is straight-forward, and reasonably easy to follow after a few moments’ thought. And it works. All the edge cases have been accounted for.
But this code should leave a bad taste in your mouth. One clue that it is a little “off” is the requirement for an if() statement at the end, which indicates that the code works differently depending on whether it’s in the middle of the list or at the beginning.
In contrast to that example, take a look at this second approach (offered as an example of much better taste):
Here we have a function that accomplishes the exact same thing as the original code, but it just tastes better. It requires less than half of the lines of code, and more importantly, there are no special cases. It just does the job that the coder intended it to – no more and no less. Yes, it requires a clear understanding of pointers (and so it might be slightly more difficult to understand, on first review), but it also provides a great example of why pointers can be so powerful. (And the useful comments take away any remaining mystery.)
So, I thought I would pass this along as a simple but helpful educational tool for communicating what good code should taste like. Because we should all become a little better connoisseurs of code.