What matters most when writing code? (Readability? Performance?)
I read this recently in a thread on software craftsmanship:
In my “craft of software development” course, I’ve noticed two competing philosophies. Several of my students believe that efficiency is the most important aspect of code, where as, I believe that code readability is the most important aspect of code.
I find similar reactions when I work with programmers. I usually respond with one of those annoying consultant phrases: it depends on the context. I wouldn’t do my job as a consultant if I didn’t also provide a more concrete answer, so I’d like to start that here. Your comments will help me refine this answer as time goes on, so please challenge me!
I don’t believe that “the most important” aspect of code can exist. No matter which important aspect of code you choose to label “most important”, we could easily spend five minutes imagining a context where some other aspect matters more than that one. For example, I can think of situations in which correctness matters surprisingly little, or speed matters surprisingly little, or maintainability matters surprisingly little. I don’t just mean trivial contexts, either, but ones drawn from the real experiences of real people. Thus, as consultants often do, my answer consists of an exercise: which aspect of code do you think is most important? Now, let’s imagine a situation in which we’d generally consider a different aspect of code even more important than this “most important” one. Repeat until bored (or convinced, or both).
Michael Feathers has suggested that “readability is the best default [most-important aspect] for nearly all code”. This seems quite reasonable, but Michael included the word “nearly” for a reason. True: in the context where people time costs more than machine time, then readability matters much more. I worry that we’ve lived in that context for so long, that we forget that we’ve made a tradeoff. Jerry Weinberg tells stories about IBM renting him free of charge to clients who buy a computer. In that context, where machine time costs so much more than people time, then shaving milliseconds probably matters more. Don’t get me wrong: absent other information, I tend towards optimizing for a balance between low cost to understand and low cost to change. (These two relate, but I can understand code that I nevertheless feel afraid to change because of high coupling to some difficult-to-understand system). If I don’t know my audience well, then I tend to tip the balance—not much, but a little—in favor of low cost to change, so that they can more readily make the code easier for them to understand.
As usual in these cases, knowing the forces matters more than choosing a sensible context-free default option.