Halstead Volume
Measures the size of a function's implementation based on operator and operand token counts.
Formula
What it measures
Halstead Volume (V), part of Maurice Halstead's 1977 software science metrics, quantifies the amount of information carried by a function. It combines the total token count (N) with the vocabulary richness (η) to produce a size estimate that is more meaningful than raw line counts.
A higher volume means the function carries more information, requires more mental effort to understand, and is more error-prone. Volume is also used to compute the Maintainability Index and Technical Debt.
How it's calculated in tsmetrics
tsmetrics classifies every AST leaf node as either an operator or an operand:
Operators (anonymous leaf tokens)
Arithmetic: + - * / % ** ·
Equality: === !== == != ·
Comparison: < > <= >= ·
Logical: && || ?? ! ·
Bitwise: & | ^ ~ << >> >>> ·
Assignment: = += -= *= /= %= **= &&= ||= ??= &= |= ^= <<= >>= >>>= ·
Update: ++ -- ·
Member access: . ?. ·
Spread/rest: ... ·
Arrow: => ·
Control flow: if else while for in of switch case default ·
Keyword operators: return new typeof instanceof delete void ·
Async/generator: await yield ·
Jump: throw break continue ·
Ternary: ?
Operands (named AST nodes)
identifier, property_identifier, this, super, number, string, template_string, true, false, null, regex
Structural punctuation (( ) { } , ;) is ignored.
Nested functions are their own units — their tokens do not contribute to the enclosing function.
TypeScript example
function add(a: number, b: number): number { return a + b; } // Operators: return(×1), +(×1) → η₁=2, N₁=2 // Operands: add(×1), a(×2), b(×2) → η₂=3, N₂=5 // η=5, N=7, V = 7 × log₂(5) ≈ 16.25
Expected output
Thresholds
Halstead Volume has no configurable violation thresholds. It is used as an input to Maintainability Index and Technical Debt and included in JSON output.
References
- Halstead, M. H. (1977). Elements of Software Science. Elsevier.
- Lanza, M. & Marinescu, R. (2006). Object-Oriented Metrics in Practice. Springer.
Related metrics
Cyclomatic Complexity · Maintainability Index · Technical Debt
Edit on GitHub