Dart Cognitive Complexity: Refactoring Recipes & Deep Module Guardrails
This reference accompanies SKILL.md and provides the full
before/after refactoring catalog (Patterns A–F), Ousterhout "Deep Modules"
decomposition rules, library boundary selection (lib/src/ vs. part /
part of), the api_summary verification workflow, and the PR provenance
template.
1. Ousterhout "Deep Modules" & Public API Surface Guardrails
Reducing per-function cognitive complexity (<= 15) and splitting oversized
files (> 400 lines) must never create shallow internal helper classes or leak
internal plumbing into a package's public API surface (lib/<pkg>.dart /
api.txt).
1.1 Deep Externally, Pure Internally (No Stateful Single-Use _Populator / _Runner Classes)
- Explicit Prohibition: Never decompose a complex function by creating
single-use stateful private helper classes (
_FooPopulator,_BarBuilder,_BazRunner) that hold mutable fields across methods or mutate caller collections (Map,Set,List) in-place. Moving local variables into mutable class fields hides data flow across parameterlessvoid _step()calls without reducing actual complexity. - Mandatory Requirement: Extract pure file-private top-level functions
(
_validateItem(...),_parseHeader(...)) orstaticmethods on existing domain types with explicit inputs and immutable return values (Dart 3 named records or immutable value types).
Anti-Pattern: Stateful Single-Use _Populator Class (Banned)
// BANNED: Single-use stateful helper class mutating fields across void methods.
class _OrderSummaryPopulator {
final List<LineItem> items;
final Map<String, double> totalsByCategory = {};
final List<String> warnings = [];
_OrderSummaryPopulator(this.items);
void populate() {
for (final item in items) {
_accumulateItem(item);
}
}
void _accumulateItem(LineItem item) {
if (item.price < 0) {
warnings.add('Negative price on ${item.id}');
return;
}
totalsByCategory.update(
item.category,
(v) => v + item.price,
ifAbsent: () => item.price,
);
}
}Preferred: Pure File-Private Top-Level Functions Returning Records
// REQUIRED: Pure file-private top-level functions with explicit inputs and
// immutable record return values.
({Map<String, double> totalsByCategory, List<String> warnings})
_summarizeOrderItems(Iterable<LineItem> items) {
final totals = <String, double>{};
final warnings = <String>[];
for (final item in items) {
final warning = _validateItem(item);
if (warning != null) {
warnings.add(warning);
continue;
}
totals.update(
item.category,
(v) => v + item.price,
ifAbsent: () => item.price,
);
}
return (
totalsByCategory: Map.unmodifiable(totals),
warnings: List.unmodifiable(warnings),
);
}
String? _validateItem(LineItem item) =>
item.price < 0 ? 'Negative price on ${item.id}' : null;1.2 Load-Bearing Library Boundary Rule (Tier 1 vs. Tier 2 When Splitting Files)
Prefer the boundary enforced by the Dart compiler (library privacy _ and class
modifiers) over advisory lint annotations (@internal, which still leaks into
api.txt when attached to members of exported classes):
- Tier 1 (Default — Standalone
lib/src/<topic>.dart): Use when extracted helpers form a genuine sub-domain with narrow parameter lists (<= 3args), require zero access to private_members of the parent class/library, and cross zero library-scoped class modifier boundaries (sealed,final,interface,base, or private generative constructors._()). Re-export only intentional public symbols via explicitexport 'src/<topic>.dart' show ...;—never unscopedexport 'src/...';. - Tier 2 (
part/part of): Use when splitting one cohesive domain where helpers share private_fields, private constructors (._()), class modifiers (sealed,final,interface,base), or internal invariants, OR when standalonelib/src/files would require widening visibility (e.g., removing_or adding@internal) and risk leaking internal types via unscopedexport 'src/...';directives.
1.3 Mandatory api_summary Public API Surface Verification Gate
Whenever a complexity or file-split refactor extracts helpers across files or
touches lib/ exports in a Dart package, verify that the public API surface did
not accidentally widen:
- Ensure package resolution and capture a non-empty baseline before
refactoring (without
.dart_tool/package_config.json,api_summarysilently exits0with only theenvironment:header and0package:entries, making a before/after diff tautologically empty):test -f .dart_tool/package_config.json || dart pub get dart run api_summary@^1.1.0 > /tmp/api_before.txt && rg -q '^package:' /tmp/api_before.txt - Capture post-refactor surface:
dart run api_summary@^1.1.0 > /tmp/api_after.txt && rg -q '^package:' /tmp/api_after.txt - Verify zero unintended public symbol leaks:
Ifdiff -u /tmp/api_before.txt /tmp/api_after.txtapi.txtis tracked in the repository, also verifygit diff api.txtis empty (or rundart run api_summary@^1.1.0 --check).
2. Dart Refactoring Pattern Catalog
Pattern A: Replace Nested If-Else with Dart 3 Switch Expression
In Dart 3, an entire exhaustive switch expression incurs a single base penalty,
regardless of how many pattern arms it contains. Converting deeply nested
if-else trees into declarative tables removes repeated branching penalties and
flattens nesting.
Before: Nested Conditional Ladders (Score: 11)
int resolveTimeout(String protocol, bool isSecure, int retryCount) {
if (protocol == 'http') {
if (isSecure) {
if (retryCount > 3) {
return 5000;
} else {
return 3000;
}
} else {
return 1000;
}
} else if (protocol == 'ftp') {
return isSecure ? 10000 : 2000;
}
return 0;
}After: Table-Driven Switch Expression (Score: 1)
int resolveTimeout(String protocol, bool isSecure, int retryCount) =>
switch ((protocol, isSecure, retryCount)) {
('http', true, > 3) => 5000,
('http', true, _) => 3000,
('http', false, _) => 1000,
('ftp', true, _) => 10000,
('ftp', false, _) => 2000,
_ => 0,
};Pattern B: Guard Clause Inversion (Flattening Nesting Depth)
Invert conditional checks into early guard return statements
(if (!condition) return;). Every early exit strips away a layer of nesting
multiplication from subsequent downstream logic.
Before: Pyramid of Nesting (Score: 11)
Future<void> syncPayload(User? user, Payload? data) async {
if (user != null) {
if (user.hasPermission) {
if (data != null && data.isValid) {
for (final item in data.items) {
await repository.save(item);
}
}
}
}
}After: Early Exit Guard Clauses (Score: 5)
Future<void> syncPayload(User? user, Payload? data) async {
if (user == null || !user.hasPermission) return;
if (data == null || !data.isValid) return;
for (final item in data.items) {
await repository.save(item);
}
}5-Step Pre-Extraction Simplification Checklist for Borderline Functions (CC 16–22)
Rule: When a function is just over the threshold (CC 16–22, needing -1
to -7 points), you MUST exhaust all 5 in-place and cross-method
simplifications before extracting ANY single-caller helper:
- Cross-Method Deduplication (
FanIn >= 2): Scan sibling methods in the same class/file for repeated logic (3+branches) and extract a shared helper called by2+methods. - Multi-Branch Local Closure Promotion: If a function passes an inline
callback/closure (e.g.
onValue: (x) { ... }) containing3+branches (if/switch/&&), every branch inside that closure pays an extra+1closure nesting penalty. Promote the closure to a named private method first. - Identical-Return Coalescing, Exception/Loop Guard Flattening & Tautological
Guard Removal: Merge
ifbranches orswitchcases that return the exact same value (if (a || b) return x;/case A || B:); coalesceon Ex { rethrow; } catch (e, s) { if (...) rethrow; }intocatch (e, s) { if (e is Ex || ...) rethrow; }; hoist pre-loop null-reader checks (if (reader == null) return ...;) and replacewhile (true) { ... if (!hasListener) break; }withwhile (hasListener); remove redundant null/type checks on expressions whose static type is already non-null or cast; and drop redundant.toList()calls after.cast<T>()when anIterable<T>suffices. Never slice atry/catchout of a retry loop with anullsentinel return, or pass a caller's mutable state flag (bool isAborted) by value into a helper that mutates it. - Twin-Block Loop Folding & Loop-Invariant Hoisting: When two consecutive
blocks perform the same structural check on two values (e.g.
inputTypeandoutputType, orserializeConfiganddeserializeConfig), fold them into a 2-element collection loop (for (final item in [?first, ?second])orfor (final t in {typeA, typeB})). If a per-item method loops over class-wide or outer-scope metadata on every call, hoist that loop to the outer orchestrator. - Zero-Nesting-Gain & Asymmetric Extraction Ban: Never extract a
single-caller helper at
callNestingDepth == 0out of a borderlineCC 16–22function whensliceScoreInPlace == sliceScoreAtRoot(0net file CC reduction), and never asymmetrically extract one arm of a peerMap/Iterableorswitchdispatch while leaving its twin inline.
Before: Twin Blocks + Identical Returns + Tautological Casts
void registerCodecTypes(
TypeDescriptor? inputType,
TypeDescriptor? outputType,
Set<Uri> imports,
) {
if (inputType != null && !inputType.isPrimitive) {
if (inputType.kind == TypeKind.scalar || inputType.kind == TypeKind.enumType) {
imports.add(inputType.libraryUri);
} else if (inputType.kind == TypeKind.alias) {
imports.add(inputType.libraryUri);
}
for (final arg in inputType.typeArguments.cast<TypeDescriptor>().toList()) {
if (arg is TypeDescriptor && !arg.isPrimitive) {
imports.add(arg.libraryUri);
}
}
}
if (outputType != null && !outputType.isPrimitive) {
if (outputType.kind == TypeKind.scalar || outputType.kind == TypeKind.enumType) {
imports.add(outputType.libraryUri);
} else if (outputType.kind == TypeKind.alias) {
imports.add(outputType.libraryUri);
}
for (final arg in outputType.typeArguments.cast<TypeDescriptor>().toList()) {
if (arg is TypeDescriptor && !arg.isPrimitive) {
imports.add(arg.libraryUri);
}
}
}
}After: Folded 2-Element Loop + Coalesced Condition + Tautological Guard Removed
void registerCodecTypes(
TypeDescriptor? inputType,
TypeDescriptor? outputType,
Set<Uri> imports,
) {
for (final type in [?inputType, ?outputType]) {
if (type.isPrimitive) continue;
if (type.kind == TypeKind.scalar ||
type.kind == TypeKind.enumType ||
type.kind == TypeKind.alias) {
imports.add(type.libraryUri);
}
for (final arg in type.typeArguments.cast<TypeDescriptor>()) {
if (!arg.isPrimitive) imports.add(arg.libraryUri);
}
}
}Pattern C: The 3-Tier Decomposition Rubric (Anti-Goodhart)
Run the companion statement-level data-flow analyzer on each candidate line slice before extracting:
dart run cognitive_complexity:data_flow@^2.0.1 lib/src/my_file.dart:45-80Its report (inputs, mutations, live outputs, control-flow escapes,
complexity impact enclosing_score / slice_score_in_place /
slice_score_at_root / estimated_enclosing_score_after,
extraction_warnings, and a synthesized Dart 3 record signature) selects the
tier. If extraction_warnings warns about high parameter count (>= 5 inputs),
low complexity payoff, or a shallow signature-to-complexity ratio, flatten in
place with Patterns A/B instead of extracting a shallow pass-through helper:
- Tier 1 — Pure Functional Decomposition (First Choice):
- Selection: Cleanly extractable slice with 2+ live outputs,
<= 4inputs, andslice_score_at_root >= 3. - Idiom: Extract a pure file-private top-level function (
_parseHeader,_validateItem) orstaticmethod returning the synthesized Dart 3 named record signature verbatim (final (:data, :errors) = _stepOne(input);). - Dataclass Boundary: Private, file-local slices use named records at ANY
output count—do not create single-use
_XxxResultdataclasses for them. Reserve dedicated dataclasses only for values that cross public API boundaries or require specialized invariants/methods. - State Scoping: If the helper does not read or mutate class instance
state (
this), declare it as a private top-level function (orstaticmethod) to guarantee referential transparency.
- Selection: Cleanly extractable slice with 2+ live outputs,
- Tier 2 — Standard Helper Extraction (Second Choice):
- Selection: Cleanly extractable slice with
<= 1live output,<= 3inputs, andslice_score_at_root >= 3. - Idiom: Extract a pure private top-level function or private helper method returning that single value.
- Selection: Cleanly extractable slice with
- Control-Flow Escapes & Loop Bodies:
- Enlarge the slice to include the entire enclosing loop or state machine and
re-run
data_flow. - If the loop body itself is the hotspot, extract it with an explicit signal
return (Pattern E)—never a
shouldBreakboolean flag. - Use guard-clause inversion (Pattern B) when the escape exists only to skip nested conditions.
- Enlarge the slice to include the entire enclosing loop or state machine and
re-run
- Tier 3 — Encapsulated Method Object (Last Resort):
- Mutation-Web Check Gate: Permitted ONLY if
data_flowreports on at least two distinct candidate slices show that the intersection of theirmutationsvariable names contains 3 or more entries (the same mutable variables thread through every candidate extraction). - Mechanics: Read
method-object.mdfor extraction mechanics and mandatory idioms. Do not load or apply it speculatively. - Domain-Modeling Exit: When the same tightly coupled mutable state keeps
resurfacing across a function (a parser's
buffer+cursor, a traversal'squeue+visited), promote it to a real, cohesively named domain class (Parser,GraphTraversal) with multiple public behaviors and its own unit test suite.
- Mutation-Web Check Gate: Permitted ONLY if
Pattern D: Fast-Fail Type Matching & Silent Data Swallowing
When refactoring loops and type checks to reduce branching, never replace explicit type casts with pattern matching that silently drops data.
Flawed Structure (Silent Failure)
for (final raw in rawTasks) {
// SILENTLY DROPS malformed data if raw is not a Map
if (raw case final Map<String, dynamic> taskMap) {
_applyTask(taskMap);
}
}Correct Structure (Fast-Fail Preservation)
for (final raw in rawTasks) {
if (raw is! Map<String, dynamic>) {
errors.add('Malformed task item (expected Map, got ${raw.runtimeType}): $raw');
continue;
}
_applyTask(raw);
}Pattern E: Loop-Body Extraction with Signal Returns
When a loop body must be extracted but contains break/continue targeting the
loop, never smuggle the control flow through boolean flags (shouldBreak soup).
Return an explicit signal and keep the loop keywords at the loop site:
enum _ScanAction { proceed, skip, halt }
// Pure, independently testable top-level helper.
_ScanAction _classify(Entry entry, Set<String> seen) {
if (seen.contains(entry.id)) return _ScanAction.skip;
if (entry.isTerminal) return _ScanAction.halt;
return _ScanAction.proceed;
}
outer:
for (final entry in entries) {
switch (_classify(entry, seen)) {
case _ScanAction.skip:
continue;
case _ScanAction.halt:
break outer;
case _ScanAction.proceed:
process(entry);
}
}Use a sealed class instead of an enum when the signal must carry a payload.
Prefer extracting the entire loop when data_flow shows it forms a natural
seam; use Pattern E when the loop body alone is the hotspot.
Pattern F: Acyclic File Decomposition (file_split)
When a Dart file grows beyond 400 lines (enforceable via opt-in
--max-file-lines 400 and --max-function-lines 60 on cognitive_complexity),
run the deterministic intra-file dependency graph advisor:
dart run cognitive_complexity:file_split@^2.0.1 lib/src/large_file.dart --target-lines 300--target-lines is a physical-line budget for the surviving file. The planner
extracts disjoint islands first, then sub-cone leaf groups out of the dominant
island (one level), names each cut after its dominant public declaration, and
skips Tier-3 part fallback cuts that would leave < 25% of the pre-fallback
file behind. The header reports largest resulting file: N lines (appending
(target M not met) when N > M; largest_resulting_file_lines and
meets_target in --format json, which always emits an array with one report
per analyzed file). Oversized-declaration notes
(implements X (n/m members are @override) / extends X, static-promotion
hints, embedded-asset hints, and coupled-SCC vs. cohesive-island summaries)
appear on both Move Declarations in extracted cuts and
Surviving Declarations: when at least half of a class's members are
@override, its size is bound by the interface surface, so promoting static
members will not help; narrow the interface or delegate instead.
Apply the Load-Bearing Library Boundary Rule (Section 1.2) when selecting
between a standalone lib/src/<topic>.dart file (Tier 1, CLI
[Cut N - Tier 1] or [Cut N - Tier 2] for 1–3 @internal widenings inside
lib/src/) and part / part of (Tier 2, reported by file_split as
[Cut N - Tier 3]), and always run the api_summary verification gate (Section
1.3) before and after splitting.
Treat the plan as advisory. The suggested cut name follows one declaration;
rename each new file after what it actually holds (shared types belong in a
models-style file), and update import sites directly instead of adding
export ... show barrels.
Pattern G: Reviewing Shallow Single-Caller Helpers (shallow, Advisory)
When you suspect over-eager decomposition left behind pass-through plumbing
(single-caller micro-helpers or high-arity bucket-brigade functions with >= 5
parameters), you can optionally run the AST shallow helper scanner as a review
aid:
dart run cognitive_complexity:shallow@^2.0.1 lib/The scanner identifies non-exported helpers with FanIn == 1 and
TestFanIn == 0 matching any of 4 structural tags (HIGH_ARITY,
MICRO_HELPER, SIG_HEAVY, CROSS_FILE_SINGLE_CALLER) and simulates the exact
caller Cognitive Complexity at the call-site nesting depth after re-inlining.
Its classifications describe what is possible, not what to do:
SAFE_INLINE(CallerCCAfter < 15): Inlining would not breach the caller's budget. Consider it only when the helper is pure plumbing; keep it when it has same-shape siblings that stay extracted, when its name or doc comment carries meaning, or when inlining an earlyreturnwould skip later caller logic (seeSKILL.mdSection 5.3).ZERO_HEADROOM(CallerCCAfter == 15): Inlining would spend the caller's last point of budget; leave extracted.FLATTEN_AND_INLINE(HelperCC <= 4,depth > 0,CallerCCAfter <= 22, and no absorbed child helpers): Only relevant when the caller is itself being fixed; flatten with Pattern A or B as part of that work.LOAD_BEARING(HelperCC >= 5orCallerCCAfter > 22): Keep extracted, or narrow its parameter list ifHIGH_ARITY.
Pattern H: Hot Inner Loops — Suppress Instead of Splitting (// cognitive_complexity:ignore)
When a function is a tight nested inner loop—such as a 2D matrix/grid row /
col scan, neighbor/penalty scoring kernel, pixel/image buffer loop, module
grid scan, or byte/token kernel—you MUST NOT extract per-cell or per-element
helpers called inside the loop body (nor split a single 2D pass into multiple
passes). Instead, you MUST keep the hot kernel inline and place
// cognitive_complexity:ignore <reason> on the line immediately preceding the
declaration:
// cognitive_complexity:ignore Hot 2D matrix neighbor-scoring kernel; keep inline to avoid per-cell call overhead.
int _scoreModules(List<int> modules, int size) {
// Keep tight row/col loops inline.
}3. Pull Request & Commit Provenance Template
When confirmed by the user in interactive sessions, include this standardized block in the PR description or commit body:
### 🤖 Tool Provenance & Complexity Delta
This refactoring was guided by
[`cognitive_complexity`](https://pub.dev/packages/cognitive_complexity)
(`v{version}`).
| Target Declaration | Pre-Score | Post-Score | Operational Ceiling |
| :--- | :---: | :---: | :---: |
| `{declaration_name}` (`{file_path}`) | `{pre_score}` | `{post_score}` | `<={threshold}` |
To reproduce or re-evaluate cognitive complexity scores:
```bash
{exact_command_line}
```
```bash
dart run cognitive_complexity:data_flow@^2.0.1 {file}:{start_line}-{end_line}
```