Writing a Good Set of Coding Conventions
- What Are Conventions For?
- Comments
- Indenting
- Braces and Blocks
- Names and Parts of Speech
- Summary
Coding conventions are the cause of holy wars throughout the developer community. A good set of coding conventions can make a huge difference to how easy a project is to maintain and even how many bugs it contains.
What Are Conventions For?
The broad aim of a set of programming conventions is that a developer should be able to read any piece of a large codebase. This is not achievable just by having a good style guide, but coherent conventions can make it easier.
A consistent style makes it much easier to write bug-free code. Most of the time when you find a bug, it is part of a family. You can look through the codebase to find places where the same mistake has been made and fix it everywhere. This is a lot easier if the same concept is expressed the same way everywhere.
Some rules in a style guide are designed to avoid bugs. A good example is the common rule in C coding conventions that you should put the r-value on the left-hand side when comparing an l-value and an r-value, for example:
if (NULL == aPointer)
The reason for this is that it's very easy to accidentally type a single equals sign by mistake. If you do that, then this will generate a compile-time error because you can't assign a value to NULL. If you write them the other way around, then NULL will be assigned to the variable and the conditional will always test false and probably be optimized away. This kind of thing is highly language-dependent. In a language with more ALGOL-like syntax, an assignment is := while a comparison is =. It is very hard to accidentally type := when you mean =, so this rule would make no sense.
The most important thing to remember when designing style guidelines (and code, for that matter) is this: Always know why you are doing something.