Class CognitiveComplexityCounter
java.lang.Object
org.ek9lang.compiler.phase5.CognitiveComplexityCounter
Tracks cognitive complexity within functions/methods/operators.
Cognitive complexity measures how difficult code is to understand, accounting for
nesting depth and EK9's unique guard expressions.
Formula: For each control structure, cost = (base_cost + guard_penalty) x nesting_depth
Base costs:
- Control structures (if, while, for, switch, try, catch, finally): 1
- Guard expression (
<-): +1 penalty (declaration + check + scoping)
Additional flat costs:
- Coalescing operators (
??,?:, etc.): 1 each - Boolean sequences (
and,or): 1 per sequence - Stream pipes beyond 3: 1 each
Key insight: EK9's guards pack more cognitive load per line than simple conditions. A 5-level guarded structure is harder to understand than 5 simple ifs.
- See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescription(package private) voidaddControlStructure(boolean hasGuard) Add cognitive cost for a control structure.(package private) voidaddFlatCost(int cost) Add flat cognitive cost (not multiplied by depth).(package private) voidIncrement depth when entering a control structure.(package private) voidDecrement depth when exiting a control structure.(package private) booleanisEmpty()Check if there are any scopes on the stack.(package private) intpopScope()Pop scope and return total cognitive complexity.(package private) voidPush new scope when entering function/method/operator.
-
Constructor Details
-
CognitiveComplexityCounter
CognitiveComplexityCounter()
-
-
Method Details
-
pushScope
void pushScope()Push new scope when entering function/method/operator. -
popScope
int popScope()Pop scope and return total cognitive complexity. Called when exiting function/method/operator.- Returns:
- the total cognitive complexity accumulated in this scope
-
enterNesting
void enterNesting()Increment depth when entering a control structure. -
exitNesting
void exitNesting()Decrement depth when exiting a control structure. -
addControlStructure
void addControlStructure(boolean hasGuard) Add cognitive cost for a control structure. Cost = (base_cost + guard_penalty) x current_depth- Parameters:
hasGuard- true if this control structure uses a guard expression (<-)
-
addFlatCost
void addFlatCost(int cost) Add flat cognitive cost (not multiplied by depth). Used for coalescing operators, boolean sequences, etc.- Parameters:
cost- the flat cost to add
-
isEmpty
boolean isEmpty()Check if there are any scopes on the stack.- Returns:
- true if stack has no contents
-