Is Your Code Hard to Understand?
Editorial Note: I originally wrote this post for the Infragistics blog.
I’ve heard a bit of conventional wisdom in the software industry. It holds that people will read a given line of code an order of magnitude more times than they’ll modify it. Whether that wisdom results from a rigorous study or not, I do not know. But it certainly squares with my experience. And it also seems to square with the experience of just about everyone else.
Accepting this wisdom as axiomatic, code readability becomes an important business concern. If you optimize for ease of writing at the cost of ease of reading, your business will lose money. Better to spend some extra time in writing your code to ensure that future readers have an easy go of it. And easy for them means that they understand the code.
You know of obvious ways to promote reader understanding in code. Don’t give variables cryptic names or names that cannot be pronounced. Don’t write gigantic methods and classes. Limit method parameters and local declarations. Read through the code out loud to see if it seems clear. These guidelines will bring you a long way toward readability.
But other, subtle concerns can also chip away at your code’s readability. I’ll list some of these here, today. These are generally C# specific, but some are more broadly applicable than that. What all of them have in common is that they constitute sources of confusion for readers that may not seem immediately obvious.