Friday, January 9, 2009

Code complexity

One of the aims of coding guidelines may be to keep code complexity as low as possible (complex meaning: hard to read, error prone).

Nested expressions
C is an orthogonal language. It allows to chain and nest expressions. This evokes the following problems:
• Code can become unreadable.
• Complicated expressions may require a operator precedence lookup, based on the assumption that one does not have all of the precedences memorized20.
• Source code debugging doesn't show intermediate data.
• Expressions need to be wrapped to a second line or the line will be extraordinary long.
Most of these points make code harder to read and debug.
You should not avoid using temporary variables in order to enhance performance. Temporary variables can be optimized away to lead to the same code that was expected from the complicated expression (if the compiler is powerful enough).
One drawback of nested expression was the warning "assignment in conditional expression" with if(p = malloc(size)). The warning can be avoided by using parentheses or by separating statements: p = malloc(size); if(p). This may additionally make debugging easier.

Redundancy
Code fragments should not be repeated.
Redundant code is harder to maintain and increases the probability of introducing defects. Code with many redundancies is harder to read.
You might consider implementing a more general function instead21.
If performance is the problem, use macros or an optimizing compiler that inlines the functions (preferred).

Determinism
Write deterministic code. Stack variables and buffers should be initialized.
Searching for bugs that show non-deterministic symptoms is an unpleasant task at best.
You may consider to assign a freed pointer 022.

0 Comments: