Code complexity is something the software community has struggled to define. In its simplest form it is often expressed in terms of LOC, or Lines-Of-Code. The more LOC, the more complex a piece of software is – or so the theory goes. The reality is quite different of course – there is no definitive way of defining the complexity of a piece of code – a 1000-line program could be made up of simple statements, or could include a plethora of logical decision, both are the same length, but the latter has an inherently more complex algorithmic/logical structure. A program with a single if-else statement has two possible paths. A similar program with 10 if-else constructs has 1024 (2^10) distinct paths making it a more complex program.
Complexity could relate to a programs complexity in terms of computational complexity or psychological complexity. A “rough” measure of computational complexity, logical complexity is a measure of the degree of decision making logic within a program, i.e. the number of “binary” decisions. If a program had 1000 statements, and 300 of those were “if” statements, then the logical complexity of the program is likely higher than if the program only had 20. Psychological complexity on the other hand refers to those characteristics of a program which make it difficult for a to human comprehend [1].
Here are some factors which affect the complexity of programs:
Program Form
- Presence or absence of well-placed, meaningful comments.
- Placement of declarations.
- Paragraphing.
- Variable names – mnemonic and length.
- Use of same variable names in an inner scope.
- Use of “magic” numbers.
Control flow
- Complexity of control flow.
- Choice of control construct.
- Length of program segments (e.g. loops)
- Passing functions as parameters.
- Recursion.
- Levels of nesting.
Data flow
- Scope of variables.
- Clustering of data references.
- Declaration and use of complex data structures.
- Use and manipulation of pointers.
[1] Chaudhary, B.D., “A study in dimensions of psychological complexity of programs”, Int. J. man-Machine Studies, 23, 113-133 (1985).