- What Are Conventions For?
- Comments
- Indenting
- Braces and Blocks
- Names and Parts of Speech
- Summary
Braces and Blocks
Most languages contain some way of splitting code into blocks. ALGOL used BEGIN and END, C uses braces, and Smalltalk uses square brackets. Irrespective of the language, the location of the braces is contentious and in some cases so is their presence.
One of the worst offenders for this is the LLVM coding conventions. These specify a line width of at most 80 characters and allow you to omit braces after if statements with only one statement in the body. Why is this a problem? Because, in C++ especially where you have very long iterator type names, you often get if statements where the condition is longer than 80 characters. These then wrap to the next line and so you can't see without reading the whole line whether it is part of the conditional or a statement.
This brings me on to the second rule for good coding conventions: Good coding conventions reduce the amount that you need to read to understand a block of code.
If you're looking at a bug in a program, then you often end up reading a lot of code around where you think the problem is. In a language that supports short-circuit evaluation of conditionals, like C, then you may be able to discount that branch after the first subexpression. You then want to jump immediately to the end of the if block.
A good set of style guidelines should make this easy. Exactly the best way of doing that depends a bit on the language. In Haskell, for example, where scope is determined by indent level, this is generally easy. In C, where it's determined by the depth of braces, then it's much harder. If you can just scan down the left margin until you come to a close brace, then it's much easier.
The other issue to think about is what happens when you do this in reverseif you identify the line containing the problem and want to find why you got there. You want to glance up the left margin and immediately see where this block started. A mixture of good brace and good indenting rules can make this a lot easier. I won't propose any hard and fast rules here, but I'll just remind you that the human eye is incredibly good at spotting symmetry…