DIMAJIX - software consulting (http://www.dimajix.de/)
 

Miscellaneous


Rule 67. Avoid embedded assignments.

Assignements embedded in if- or while-conditions are hard to read and may confuse another code maintainer. Examples for embedded assignements are:

// Bad Style
unsigned int result;
if (result = calculateSum()) {
    ...
    
// Bad Style
unsigned int result;
if ((result = calculateSum()) > 0) {
    ...

// Good style
unsigned int result = calculateSum();
if (result > 0) {
    ...


Rule 68. One line contains at most one statement.

More than one statement per line is much harder to read and to understand. In many cases it is even a good idea to insert empty lines between logical code blocks in order to organize the code.


Rule 69. Avoid the use of numeric values in code; use symbolic values instead.

Numeric values in switch-cases are always something very fragile, because in that case it is obviously not the numerical value as such that is important but the interpretation as a message or flag. The usage of symbolic values enhances the readability and simplifies later changes. In order to define these symbolic values you should either use enum's or static const int's, but never #define's.

// Bad and error prone style
switch(mode) {
    case 1:
        ...
        break;
    case 2:
    case 3:
        ...
    default:
        ...
}



// Good Style
enum Mode {
    ColourMode = 1,
    BlackWhiteMode = 2,
    GrayMode = 3,
};

...

switch(mode) {
    case ColourMode:
        ...
        break;
    case BlackWhiteMode:
    case GrayMode:
        ...
        break;
    default:
        ...
}

Another advantage of using enum's instead of numerical values or #define's is that functions declared with an enum as a parameter will result in a compiler error when an integer is used in a call. This helps to find bugs at compliation time.


Rule 70. A switch statement must always contain a default branch which handles unexpected cases.

Kaya Memisoglu 2005-01-06