Skip to content
Back to skills

Low Complexity

ASecurity

Enforce low Cognitive Complexity (SonarSource) and low Cyclomatic Complexity in ALL code written or modified, in any programming language, framework, or platform, preferring flat code (guard clauses, early returns) over single-use helper functions. This skill MUST activate automatically whenever code is being written, generated, modified, or refactored — no explicit trigger needed. Triggers include writing any function, method, class, module, script, handler, endpoint, test, or code block. Al...

  • 9 stars
  • 0 votes
  • 0 copies
  • 3 views
  • Added June 5, 2026
ai-agentsjavascriptpythongojavaexpress

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned November 26, 2026

npx -y skills add mryll/skills --skill low-complexity --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Low Complexity?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Low Complexity
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/mryll-low-complexity/badge)](https://www.skillsdirectory.com/skills/mryll-low-complexity)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: low-complexity
version: 1.1.0
description: Enforce low Cognitive Complexity (SonarSource) and low Cyclomatic Complexity in ALL code written or modified, in any programming language, framework, or platform, preferring flat code (guard clauses, early returns) over single-use helper functions. This skill MUST activate automatically whenever code is being written, generated, modified, or refactored — no explicit trigger needed. Triggers include writing any function, method, class, module, script, handler, endpoint, test, or code block. Also triggers on "low complexity", "cognitive complexity", "cyclomatic complexity", "reduce complexity", "simplify code", "too complex", "refactor for readability", "clean code", "implement", "fix bug", "add feature", "generate test", "optimize", "rewrite", "scaffold".
---

# Low Complexity Code

Every function/method written or modified MUST target:
- **Cognitive Complexity <= 5** (SonarSource metric). Acceptable up to 10 for inherently complex logic. Hard limit 15.
- **Cyclomatic Complexity**: hard limit 15. Each guard clause adds 1 here, so a long flat function with many early returns can score high without being hard to read. Do not split a flat function only to lower this number.

The targets (5, 10) are met by flattening only. **Only a hard limit can justify extracting a single-use function.** If the repository configures a complexity linter (for example `gocognit`, `gocyclo`, Sonar quality gates), its thresholds are the hard limits and replace the 15 above.

For full scoring rules, see [cognitive-complexity-spec.md](references/cognitive-complexity-spec.md).

## Flat, Not Fragmented

Lower complexity by flattening the code, not by spreading it across functions. A reader should be able to read a function top to bottom without jumping elsewhere.

- **Flatten first.** Guard clauses and early returns keep the normal path at the lowest indentation (Go calls this "indent error flow"). Each step that can fail ends right there.
- **A function exists only if more than one place calls it.** Do not extract a helper that has a single caller just to lower a score: inline it into its caller, even if the caller gets longer. If understanding one function requires reading another, the split is wrong (Ousterhout's "conjoined methods"). Count call sites: two calls inside the same function are two places. A function handed to a framework as an entry point (a handler, a callback) counts as called from that framework.
- **Shared ending for early returns.** When every early return must run the same final steps (log, cleanup, respond), put those steps in one function and call it right before each `return`. It has many call sites, so it follows the rule above, and the main function stays flat instead of wrapping its steps in a closure or a single-use `evaluate()`.
- **Extract as a last resort.** Extract a single-use block only when the function still exceeds a hard limit after every flattening technique below, and say why in a comment.
- **Length is not the problem; nesting is.** A long flat function is easier to read than the same logic split into small single-use functions. Keep a function within one screen when that is possible without new single-use helpers.

## Cognitive Complexity Quick Reference

**+1 for each:** `if`, ternary (`? :`), `switch` (whole), `for`, `while`, `do while`, `catch`, `else if`, `else`, `goto LABEL`, `break/continue LABEL`, each method in a recursion cycle, each sequence of like boolean operators (`&&` / `||`).

**+1 nesting penalty** on top of structural increment for: `if`, ternary, `switch`, `for`, `while`, `catch` — when nested inside another flow-break structure.

**Free (no increment):** method calls, `try`, `finally`, `case` labels, null-coalescing (`?.`, `??`), early `return`, simple `break`/`continue`, lambdas (but lambdas increase nesting level).

## Cyclomatic Complexity Quick Reference

+1 for the method entry, +1 for each: `if`, `else if`, `for`, `while`, `do while`, `case`, `catch`, `&&`, `||`, ternary `?`. Core definition; some analyzers may vary by language.

## Mandatory Reduction Techniques

Apply these in order of preference:

1. **Early return / guard clause** — Invert condition, return early, reduce nesting by 1 level. First choice.
2. **Replace nested conditions with flat logic** — `if A { if B {` becomes `if A && B {` (saves nesting penalty).
3. **Replace flag variables with early exit** — Eliminate boolean flags that control flow later.
4. **Use language idioms** — Null-coalescing, optional chaining, pattern matching, destructuring. These are often lower-cost than equivalent if/else chains (destructuring is free; pattern matching is +1 for the whole match vs +1 per branch in if/else).
5. **Decompose boolean expressions** — Put complex conditions into named boolean variables. A predicate function only if more than one place uses it.
6. **Replace loop + condition with declarative pipeline** — `filter/map/reduce` or LINQ or streams instead of `for` + `if`.
7. **Replace if/else chains with a lookup table, polymorphism, or a strategy** — Eliminates branching entirely. Only when the branches are many and data-like.
8. **Extract method/function** — Only for a block that more than one place uses, or as a last resort when the function still exceeds the limit (see "Flat, Not Fragmented"). Never a helper with a single caller just to lower a score.

## How to Apply

When writing any function/method:

1. Write the logic
2. Mentally count: each `if/else if/else/for/while/switch/catch/ternary` = +1, each nesting level on structural ones = +1 more, each boolean operator sequence = +1
3. If the cognitive score > 5, flatten using the techniques above, in order, before finalizing. Extract only if a hard limit is still exceeded
4. Prefer one flat function over several single-use functions
5. Nesting depth > 2 is a smell — flatten it with guard clauses and early returns

## Bad vs Good Examples

### Bad: Nested conditionals (CogC = 9)
```python
def process(user, order):
    if user.is_active:                    # +1
        if order.is_valid:                # +2 (nesting=1)
            if order.total > 100:         # +3 (nesting=2)
                apply_discount(order)
            else:                         # +1
                charge_full(order)
        else:                             # +1
            raise InvalidOrder()
    else:                                 # +1
        raise InactiveUser()              # Total: 1+2+3+1+1+1 = 9
```

### Good: Guard clauses, one flat function (CogC = 3)
```python
def process(user, order):               # CogC = 3
    if not user.is_active:                # +1
        raise InactiveUser()
    if not order.is_valid:                # +1
        raise InvalidOrder()
    if order.total > 100:                 # +1
        apply_discount(order)
        return
    charge_full(order)
```

No `charge()` helper: it would have one caller, and the reader would have to jump to it.

### Bad: Loop with nested conditions (CogC = 10)
```javascript
function findFirst(items, criteria) {
  for (const item of items) {              // +1
    if (item.active) {                     // +2 (nesting=1)
      if (item.type === criteria.type) {   // +3 (nesting=2)
        if (item.score > criteria.min) {   // +4 (nesting=3)
          return item;
        }
      }
    }
  }                                        // Total: 1+2+3+4 = 10
  return null;
}
```

### Good: Flat loop with a named condition (CogC = 4)
```javascript
function findFirst(items, criteria) {      // CogC = 4
  for (const item of items) {              // +1
    const matches = item.active            // +1 (&& sequence)
      && item.type === criteria.type
      && item.score > criteria.min;
    if (matches) return item;              // +2 (nesting=1)
  }
  return null;
}
```

The condition is a named variable, not a `matches()` function: only this loop uses it.

Files in this skill

  • SKILL.md5.5 KB
  • references/cognitive-complexity-spec.md4.4 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.