|
| 1 | +# Halstead Complexity Analysis |
| 2 | + |
| 3 | +Halstead metrics are a set of software metrics introduced by Maurice Halstead to measure the complexity of code based on operators and operands. These metrics help estimate code maintainability, understandability, and potential error rates. |
| 4 | + |
| 5 | +## What are Halstead Metrics? |
| 6 | + |
| 7 | +Halstead metrics are calculated using the following quantities: |
| 8 | + |
| 9 | +- **n₁**: Number of distinct operators |
| 10 | +- **n₂**: Number of distinct operands |
| 11 | +- **N₁**: Total number of operators |
| 12 | +- **N₂**: Total number of operands |
| 13 | + |
| 14 | +From these, several derived metrics are calculated: |
| 15 | + |
| 16 | +| Metric | Formula | Description | |
| 17 | +|----------------|-----------------------------------------------------|--------------------------------------------------| |
| 18 | +| Vocabulary | n = n₁ + n₂ | Number of unique operators and operands | |
| 19 | +| Length | N = N₁ + N₂ | Total number of operators and operands | |
| 20 | +| Volume | V = N × log₂(n) | Size of the implementation | |
| 21 | +| Difficulty | D = (n₁ / 2) × (N₂ / n₂) | Effort required to understand the code | |
| 22 | +| Effort | E = D × V | Mental effort to develop or maintain the code | |
| 23 | +| Bugs | B = V / 3000 | Estimated number of errors | |
| 24 | +| Time | T = E / 18 | Estimated time to implement (seconds) | |
| 25 | + |
| 26 | +## Why Use Halstead Metrics? |
| 27 | + |
| 28 | +- **Maintainability**: High Halstead volume or effort may indicate code that is hard to maintain. |
| 29 | +- **Understandability**: Difficulty and effort metrics help identify code that may be hard to understand. |
| 30 | +- **Error Prediction**: The bugs metric provides a rough estimate of potential defects. |
| 31 | + |
| 32 | +## How Are Halstead Metrics Used in This Tool? |
| 33 | + |
| 34 | +When enabled in the configuration, Halstead metrics are calculated for each class and method. The results can be displayed alongside other complexity metrics to give a more complete picture of code quality. |
| 35 | + |
| 36 | +To enable Halstead metrics in the output, set the following in your configuration file: |
| 37 | + |
| 38 | +```yaml |
| 39 | +cognitive: |
| 40 | + showHalsteadComplexity: true |
| 41 | +``` |
| 42 | +
|
| 43 | +## Interpretation |
| 44 | +
|
| 45 | +- **Low Volume/Effort**: Code is likely simple and easy to maintain. |
| 46 | +- **High Volume/Effort**: Consider refactoring; code may be hard to understand or error-prone. |
| 47 | +- **Bugs**: Use as a rough indicator, not an absolute prediction. |
| 48 | +
|
| 49 | +## References |
| 50 | +
|
| 51 | +- [Wikipedia: Halstead complexity measures](https://en.wikipedia.org/wiki/Halstead_complexity_measures) |
| 52 | +
|
| 53 | +
|
0 commit comments