Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Coverage and Technical Debt

Duplications, Cyclomatic and Cognitive Complexity in SonarQube

How SonarQube finds duplicated code, how cyclomatic and cognitive complexity differ, which thresholds trigger issues, and how to try both ideas with runnable stand-ins.

Two measures describe how hard code is to change: duplication (the same logic copied in several places) and complexity (how many paths and how much nesting a reader must hold in their head). SonarQube measures both, reports them per file, and lets the quality gate limit duplication on new code.

The server cannot run on this site, so the TryIts below are simplified stand-ins that show the idea, not the product's actual algorithms.

Duplications

SonarQube searches for duplicated blocks, sequences of code that appear more than once. A block counts when it is long enough; the thresholds depend on the language. The commonly quoted rule: for most languages, at least 100 successive duplicated tokens spread over a minimum number of lines; for Java, 10 successive duplicated statements regardless of tokens and lines. Whitespace and comments do not matter, and differences in formatting are ignored.

Metrics:

Key Meaning
duplicated_lines Lines involved in duplicated blocks
duplicated_blocks Number of duplicated blocks
duplicated_files Files with at least one duplicated block
duplicated_lines_density Duplicated lines divided by total lines, as a percentage
new_duplicated_lines_density The same for new code

The default Sonar way gate requires duplicated lines on new code to be at most 3%. In the project's Measures > Duplications view you can open a file and see the other places the same lines appear, including cross-file matches within the project. Duplication across different projects is not detected, except in some editions that offer cross-project duplication checks (an Enterprise-level capability for some languages).

Why it matters

Fixes get applied in one copy and not in the others. Duplication is also a cheap way to produce inconsistent behaviour. Remove it by extracting a function, a base class or a shared module.

Exclusions

Generated code and test fixtures can be excluded from duplication checks with sonar.cpd.exclusions (for example **/generated/**). Exclude only code you do not hand-maintain.

Stand-in: a naive duplicate finder

This block hashes each window of three normalised lines and reports windows that appear more than once. Real detection works on tokens and statements, but the idea of "find repeated sequences" is the same.

JS Stand-in: find repeated 3-line windows

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

No output.

The density is the number the gate compares to 3% on new code.

Complexity: cyclomatic

Cyclomatic complexity counts the independent paths through code: start at 1 and add 1 for each if, loop, case, catch, && and || (the exact list depends on the language). It is metric complexity. It suggests how many test cases you need to cover every branch.

Its weakness: a switch with ten simple cases scores 10 and looks scary although it is easy to read, while three nested loops with an if in the middle score less than that and are hard to read.

Complexity: cognitive

Cognitive complexity (metric cognitive_complexity) was designed to match how humans read code. The rules in brief:

  1. Ignore structures that make code shorter to read (a method call replacing many lines, a switch counts as one, not per case).
  2. Add 1 for each break in linear flow: if, else if, else, for, while, catch, ternary, a sequence of mixed boolean operators, break/continue to a label, and recursion.
  3. Add an extra increment per level of nesting for nested flow-breaking structures.

So a flat if costs 1; the same if inside a for costs 2 (1 + 1 nesting); inside a for inside a for it costs 3. The default rule Cognitive Complexity of functions should not be too high (S3776) raises a code smell when a function exceeds 15 (the threshold is configurable per quality profile). The debt grows with the excess.

Refactoring cues

  • Return early with guard clauses to remove else nesting.
  • Extract the inner loop body into a function.
  • Replace long condition chains with lookup tables or polymorphism.

Stand-in: a rough cognitive score

The scorer below reads a pseudo-code outline, where each line is if, for, else, or stmt with a depth, and applies the nesting rule. It is a teaching model of the increments, not an analyzer of real code.

JS Stand-in: nesting-aware complexity score

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

No output.

The nested version scores 1 + 2 + 3 + 4 = 10 even though it has the same number of branches as the flat one (4). That gap is the whole point of the measure.

Using the numbers

  • Per-file view: Measures > Complexity, sorted descending, shows hotspots for refactoring.
  • Quality gate: complexity is not part of the Sonar way gate, but you can add a condition in a custom gate, or rely on the S3776 rule showing up as new issues on pull requests.
  • Pull request review: check "new duplicated lines" together with new issues so reviewers see both.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which metric does the default Sonar way gate limit on new code?

    The default gate asks for duplicated lines on new code to be at most 3%.
  2. 2. Which code scores higher on cognitive complexity?

    Cognitive complexity adds extra points for nesting, so the nested loops cost more than a flat switch.
  3. 3. Which property excludes generated files from duplication detection?

    sonar.cpd.exclusions removes files from copy-paste detection.
  4. 4. What is a good first step to reduce nesting?

    Guard clauses flatten nesting, which lowers cognitive complexity.

Summary

  • Duplicated blocks are repeated statement or token sequences; the gate limits new duplicated lines to 3%.
  • Cyclomatic complexity counts paths; cognitive complexity counts reading difficulty with nesting penalties.
  • The default function threshold for cognitive complexity is 15.
  • Exclude only generated code, and remove duplication by extraction.

Next: Where analysis fits in a CI pipeline