It can be difficult to write clean code, that is easy to understand, split in nice and well-defined functions that do one thing but do it well, with good variables names, and so on. For the maintainability, it is really important.
In fact, a code is read far more often than it is written. For fixing a bug, adding a feature, or simply see how it is implemented.
There are some general advices, for example:
- A function’s name should be sufficient to know all what the function really does.
- Hide implementation details, and use the domain-specific vocabulary, no technical words, if possible. An extreme example:
get_last_document()is better than
- Avoid focusing on performance from the beginning. About 10% of the code is responsible of 90% of the execution time. An optimized code is more difficult to understand, so it is better to optimize only the 10%.
Every Details Matters
Small details can also improve the code readability. Take for example this line:
g_return_if_fail (foo >= min_value && foo <= max_value);
And compare it with this one:
g_return_if_fail (min_value <= foo && foo <= max_value);
Which one do you prefer? In the second sample, we can visually see the
foo variable between the minimum and maximum values.
Many such small improvements, taken together, make the code more enjoyable to read.
We can learn these and other advices by reading some (good) existent code, by working with more experienced developers, AND by sitting in a comfortable sofa with a cup of coffee or tea while reading a book.
Although the editor of Code Complete is Microsoft Press, the book is not related to Microsoft or Windows. The author explains sometimes stuff related to open source, UNIX and Linux, but one can regret the total absence of the mention “free software” and all the benefits of freedom: be able to learn by reading other’s code, etc. But if you are here, you already know all of this, because you are on the good side 😉