Any fool can write code that a computer can understand. Good programmers write code that humans can understand. Martin Fowler, 2008.
Indeed, most of the time we spend programming is reading code. Either code written by somebody else, code we’ve written months ago, or the function that we just wrote. Therefore, all the time spent trying to improve the quality of the code we write is time we save when we are going to read it.
It is much more profitable losing a couple of minutes thinking what is the best name for a variable, or what is the best way to structure a class and get this extra time every time we have to read it, than using the first name or structure that comes to mind in order to save time having to spend it later trying to understand what a certain function does and how it does it.
A lot of times I see references to the fact that when we are programming, we are writing code to be read by somebody, in other words, we write for people and not for the compiler, but I don’t see that concern every time in the code I read.
I’ve read two very simple ideas that I kept in mind and use as motivation to keep my code the most readable possible and I try to tell to those who I come across:
Program like if the most grumpy and snappy person that you can think of was going to read and maintain your code… In other words, somebody who didn’t get very satisfied when they had to waste one or two hours of their time trying to understand what the heck the function called “Do Things” is supposed to do. Writing code thinking constantly in facilitating the life of who is going to read it, to solve problems or add functionality, makes you pay more attention to details like the variables and functions names, it forces you to have a better structure of classes. It makes you invest more time looking for good practices and the best way to apply them.
Every time you look at an algorithm you just developed with the feeling you are the smartest programmer you have ever met for doing something so complex and genious… write it again. Even if you have to write more code lines, it’s better having an easier algorithm to read than having two or three code lines that nobody understands, not even you when you go back to look at it after a couple of weeks.
I think that the importance of writing code with a high level of readability is not only the most obvious advantages like the reduction of the number of bugs or how easy it becomes to develop the application. Having an application where it is clear what each class represents, what each function does, what is the goal of each variable and where everything makes sense increases your motivation to do new things, to constantly get better. In cases where the application is kept by a team, it gives power to the involvement of different elements, even from the most juniors who feel more confident to make changes and contribute to new features.