Skip to content

Halstead's Theory

Halstead’s Metrics, also known as Halstead’s Theory, are a set of software measures used to evaluate the complexity and quality of source code. These metrics are primarily based on the count of operators and operands within a program.

Core Definitions

Halstead identifies four primary measurements for a program:

  • $n_1$: The number of distinct operators that appear in a program.
  • $n_2$: The number of distinct operands that appear in a program.
  • $N_1$: The total number of operator occurrences.
  • $N_2$: The total number of operand occurrences.

The Halstead Formulas

Using the core measurements above, several metrics are calculated to determine the program's complexity and the effort required to develop it:

  • Length ($N$): $N = n_1 \log_2 n_1 + n_2 \log_2 n_2$.
  • Volume ($V$): $V = N \log_2(n_1 + n_2)$, which represents the size of the program in bits.
  • Level ($L$): $L = \frac{2}{n_1} \times \frac{n_2}{N_2}$.
  • Difficulty ($D$): $D = 1 / L$ (or $D = \frac{n_1}{2} \times \frac{N_2}{n_2}$).
  • Effort ($E$): $E = V \times D$.

Counting Rules (C Language)

To ensure consistent measurement, specific rules are applied when counting operators and operands in C:

  • What to Ignore: Comments, identifier declarations, function declarations, and hash directives (#) are not counted.
  • Operands: All variables and constants are considered operands. Labels used with GOTO statements are also counted as operands.
  • Operators:
    • Function calls, looping statements (do-while, while, for), and control statements (if-else, switch, case) are all counted as operators.
    • Reserved words like return, default, continue, break, and sizeof are operators.
    • All brackets, commas, and terminators are counted as operators.
    • GOTO is an operator.
    • Array brackets ([]) and structure member accessors (., ->) are operators.
  • Special Handling: Unary and binary occurrences of + and - are counted separately, as is the multiplication operator *.
  • Scope Rules: Global variables are counted as multiple occurrences of the same variable across modules, while local variables with the same name in different functions are treated as unique operands.

Application to Testing

Halstead metrics can also be applied specifically to the testing phase to determine the Program Level ($PL$):

  • $PL = \frac{1}{(n_1/2) \times (N_2/n_2)}$.
  • Testing Effort ($e$): $e = V / PL$.

Practical Example

A standard sort function example shows how these are applied in practice:

  • Operators ($n_1=14, N_1=53$): Includes int, (), ,, [], if, <, ;, for, =, -, <=, ++, return, and {}.
  • Operands ($n_2=10, N_2=38$): Includes sort, x, n, i, j, save, im1, and constants 2, 1, and 0.
  • Resulting Volume: $V = 417.23$ bits.