Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Rules and Quality Gates

Complexity and Duplication

Learn how SonarQube measures cyclomatic and cognitive complexity and finds duplicated blocks, with runnable Python calculators that mimic both metrics.

Two measures drive most maintainability findings: complexity (how hard a function is to understand) and duplication (how much code is copied). Both are easy to compute and easy to misunderstand. This lesson explains how SonarQube defines them and gives you stand-ins that compute simplified versions on Python code.

Cyclomatic complexity

Cyclomatic complexity counts the number of independent paths through a function: start at 1 and add 1 for each decision (if, elif, loop, case, catch, each && or ||). It tells you the minimum number of tests needed to cover every branch. SonarQube reports it per function, file and project (the complexity measure).

Its weakness: it treats every decision the same. A flat switch with ten cases scores 10, though it is easy to read, while a deeply nested pyramid of three ifs scores 4 yet is much harder to follow.

Cognitive complexity

Cognitive complexity was designed by SonarSource to match how people read code. Its principles are:

  1. Ignore structures that make code shorter and more readable (a method call replaces many lines).
  2. Add a point for each break in the linear flow: if, else if, else, loops, catch, ternaries, jumps to labels, and sequences of different boolean operators.
  3. Add an extra point for each level of nesting of such structures. A nested if inside a loop costs more than a flat one.

Rule S3776 ("Cognitive Complexity of functions should not be too high") raises an issue when a function exceeds a threshold, 15 by default, and you can change the parameter in the profile (see Rules and Quality Profiles).

Python A simplified cognitive complexity calculator (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Run it: flat scores 3 (three flat decisions), while nested, with the same count of decisions, scores much more, because each level of nesting adds to the cost. This simplified calculator ignores else branches, recursion and some operators, so it will not match SonarQube exactly; use it to build intuition, and use the real analysis for numbers.

How to reduce complexity

  • Return early (guard clauses) instead of nesting.
  • Extract functions with a good name for each branch body.
  • Replace conditionals with data: a dictionary lookup instead of an if ladder.
  • Split long boolean expressions into named variables.

Duplication

SonarQube detects copy-paste with a token-based algorithm: it looks for sequences of tokens that repeat, ignoring formatting and comments. A block counts as duplicated when it exceeds a language-specific minimum (for example 10 consecutive statements and 100 tokens for Java, with other languages using similar amounts). The relevant measures are:

  • Duplicated blocks: how many blocks
  • Duplicated lines: lines covered by duplication
  • Duplicated lines (%), also called density: duplicated lines divided by total lines

The Sonar way gate allows at most 3% duplicated lines on new code. Duplication is a maintainability issue because a fix must be repeated in every copy, and copies drift apart.

Python Find duplicated line blocks (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real engines compare tokens rather than lines, so renaming a variable does not hide a duplicate. The stand-in is line-based for clarity.

Dealing with duplication

  • Extract the shared code into a function or class and call it from both places.
  • Accept duplication when it is deliberate and small (for example generated code or tests with similar fixtures) and exclude those files from duplication detection with sonar.cpd.exclusions (see Exclusions and Test Sources).
  • Prefer fixing duplication on new code first; the gate asks for exactly that.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does cognitive complexity add compared with cyclomatic complexity?

    Cognitive complexity adds extra points for nested structures, which better reflects reading effort.
  2. 2. What is the default threshold of rule S3776?

    The default cognitive complexity threshold is 15, adjustable in the quality profile.
  3. 3. How does SonarQube detect duplication?

    A token-based algorithm finds repeated sequences above a language-specific minimum size.
  4. 4. Which technique reduces complexity?

    Guard clauses and small well-named functions flatten the flow and reduce cognitive load.

Summary

  • Cyclomatic complexity counts paths; cognitive complexity counts reading effort and penalizes nesting.
  • Rule S3776 flags functions above a threshold (15 by default).
  • Duplication is found by token matching; the gate limits it on new code (3% in Sonar way).
  • Reduce complexity with guard clauses, extraction and data tables; reduce duplication by sharing code.

Next: The Scanner Command Line