Minimize surprize for the maintainer.
This simple rule sounds too altruistic. Why should the coder care about the maintainer?
The answer is in the law of Karma. As you saw, so will you reap.
If you are not of religious, think selfish. (Even if you are religious, I won’t stop you from thinking selfish.) What if maintenance of the code hits you after you have moved away from the code? Unless you are hoping jobs as if there is no tomorrow, practice of compassionate programming is going to help you first.
No matter how much we despise QA, bugs surface. No matter how much we get angry at the marketing folks, requirements change. Requirement changes and bugs will force you to go through your own creativity. What appeared as job security while coding would come back as curse during maintainance.
Compassion is the key. But how does that key look like? How could you be compassionate to the maintainer when the designer was not compassionate to you?
Reduction of surprise translates in reduction in indentation of the code. It also translates in writing the code as soporific and not as a candidate of “understand me if you can” challenge. While most of us most of the time don’t intend to write hard to understand code, we inadevertantly end up writing it.
Writing less indented code is under your control only in part. Bad design can undo a lot of good effort from bona-fide coder in this area.
However, if we reduce the control structures we use, we force patterns in coding. Once we force patterns, the maintainer has to think less.
Then, what control structures should be our choice? Theoretically just two of them suffice – “if” and “goto”.
Wait a moment! Am I asking you to throw all progress in methodologies in a garbage can? “goto” is the sworn enemy of a good design, isn’t it? And what about all my grudge against “if” in the same blog?
I did not suggest to converge to the theoretical minimal of flow controls. I am a fan of methodologies and suspicious of most “if”s written in the world. Then what in the good computer am I talking about?
Here is the list of my preferences: (I am going to expound on each of them in future postings)
1. “goto” – think of slimmer functions
2. “not” – think positive
3. “else” – minimize surprize
4. “else if” – just in case … – and rswitch
5. “if” – only if …
6. “switch” – did you consult a domain expert?
7. How to not to avoid decisions?
8. “while”, “do-while” and “for” – choose one
9. Why do I love associative arrays? Separation of Rule Base, Data Base and Object hierarchy?
10. Why do I love programming by contract? OOP? AOP?
I think I will stop here and then write a posting on each of the above.