A .NET tool for the CRAP (Change Risk Anti-Pattern) metric, inspired by Robert C. Martin's crap4clj, crap4java and crap4go. Combines cyclomatic complexity with test coverage to flag methods that are both complex and under-tested:
CRAP = CC² × (1 - coverage)³ + CC
The package ID is SincGmbH.Crap4Dotnet. The command is crap4dotnet.
dotnet tool install --global SincGmbH.Crap4DotnetTo build the package from this repo and install it from the local folder:
dotnet pack src/Crap4Dotnet.Cli -o nupkg
dotnet tool install --global SincGmbH.Crap4Dotnet --add-source ./nupkgThe package called Crap4DotNet on nuget.org is a different project
(7Factor/crap4dotnet). Do not
install it by mistake: use the ID SincGmbH.Crap4Dotnet.
crap4dotnet [module-filter ...]
-h, --help Show this help text.
-p, --project <path> Path to a .csproj. May be repeated.
-s, --solution <path> Path to a .sln or .slnx. Default: discover one in cwd.
--use-existing-coverage Skip running `dotnet test`; use existing coverage file.
--coverage-path <path> Cobertura XML to read. Default: all **/TestResults/**/coverage.cobertura.xml, merged.
--lcov <path> Read LCOV instead of Cobertura.
--coverage-command <cmd> Custom command to run instead of `dotnet test <solution> --collect:"XPlat Code Coverage"`.
Passed to the shell (cmd /c or sh -c) as given.
--cognitive-threshold [n] Fail (exit 2) if any member's cognitive complexity exceeds n. Default n: 15.
--crap-threshold [n] Fail (exit 2) if any member's CRAP score exceeds n. Default n: 30.
--baseline <path> With --crap-threshold: fail only on members that are new or worse than in <path>.
--output <path> Write the report to <path>. Default: .metrics/crap.json.
--min-crap <n> Hide entries with a CRAP score below n in the table only (report file and gates see all entries).
module-filter optional project/namespace-name fragment(s) to restrict analysis
By default, running crap4dotnet with no arguments discovers the single
.sln or .slnx in the current directory (a .slnx wins over a .sln of
the same name), runs dotnet test <solution> --collect:"XPlat Code Coverage",
analyzes every non-test project, prints a sorted (worst-first) table, and
writes a .metrics/crap.json snapshot.
Full solution, running tests fresh:
crap4dotnetReuse an existing Cobertura report instead of re-running tests:
crap4dotnet --use-existing-coverage --coverage-path TestResults/coverage.cobertura.xmlReuse an LCOV report:
crap4dotnet --use-existing-coverage --lcov coverage.lcovPoint at specific projects instead of a solution:
crap4dotnet -p src/MyApp/MyApp.csproj -p src/MyLib/MyLib.csprojNarrow analysis to a module/namespace fragment:
crap4dotnet BillingUse a custom coverage-collection command:
crap4dotnet --coverage-command 'dotnet test --collect:"XPlat Code Coverage" --filter Category=Unit'The command runs exactly as given, in cmd.exe on Windows and /bin/sh
elsewhere. Use double quotes inside it: cmd.exe does not treat single
quotes as quotes. The outer single quotes in the examples are for bash and
PowerShell.
Fail the build when a member is too hard to read (cognitive complexity above 15, or above a limit you give):
crap4dotnet --cognitive-threshold
crap4dotnet --cognitive-threshold 10Fail the build when a member's CRAP score is above 30 (or a limit you give), and let old code stay as it is with a baseline:
crap4dotnet --crap-threshold
crap4dotnet --crap-threshold 30 --baseline .metrics/crap.json --output .metrics/crap.after.jsonNext to cyclomatic complexity (CC), every row shows a cognitive complexity
score (Cog; cognitiveComplexity in .metrics/crap.json). Cyclomatic
complexity counts paths, which tells you how many tests a member needs.
Cognitive complexity measures how hard the member is to read. The table stays
sorted by CRAP.
CRAP Report
===========
Function Namespace CC Cog Cov% CRAP
---------------------------------------------------------------------------------------------
SingleIfMethod FixtureApp 2 1 75.0% 2.1
TrivialMethod FixtureApp 1 0 100.0% 1.0
The metric is defined in G. Ann Campbell's whitepaper Cognitive Complexity: a new way of measuring understandability (SonarSource, v1.7, 2023). The scoring follows SonarSource's rule S3776 as sonar-dotnet implements it, so the numbers match SonarQube apart from a short list of deviations (ADR-0015). Where the whitepaper and sonar-dotnet differ, sonar-dotnet decides. In short:
if, ternary?:,switch, switch expression, loops andcatchadd 1 plus the current nesting level, and raise the nesting level inside them.gotoadds 1 plus the nesting level, but does not raise it.elseandelse ifadd a flat 1. Anelse ifchain is scored as a flat chain; anifinside anelse { }block is scored as nested.- A run of the same boolean operator (
a && b && c) adds 1; each change between&&and||adds 1 more.and/orpatterns follow the same rule. - A member that calls itself adds 1 once.
- Lambdas and anonymous methods raise the nesting level for their body; their code counts toward the enclosing member.
- A local function has its own row. Its score starts at the nesting level where it is declared, plus 1. The enclosing member does not include its code.
C# 8+ conventions: a switch expression costs the same as a switch statement,
no matter how many arms it has. when guards, is patterns and not
patterns add nothing by themselves. ??, ??=, ?. and ?[] add nothing.
- The whitepaper gives no threshold and cites no empirical study. It says cyclomatic complexity measures how testable code is, and cognitive complexity how readable it is. Its scores are meant for comparing members with each other, not as a fixed limit.
- 15 is SonarQube's default limit per function in C#, Java, Python and JavaScript/TypeScript. It is a setting in the rule's code, and no published reason is given for it.
- The only independent study (Muñoz Barón, Wyrich, Wagner, ESEM 2020) found that a higher cognitive complexity goes with longer reading time. It gives no threshold, because almost none of the code it studied scored above 15. Its advice is to keep the score "as low as possible".
- The CRAP limit of 30 (Savoia) was chosen from examples and opinions, not from data. Uncle Bob's crap4java fails above 8.
No published standard gives a target, so the following is a recommendation, not a standard:
- Keep CRAP below 5 and add
--cognitive-threshold 5, which fails any member with a cognitive complexity of 6 or more. - CRAP below 5 already limits cyclomatic complexity to 4, but it still lets
deep nesting through: three nested
ifs score a cognitive complexity of 6. A limit of 5 closes that gap, while two levels of nesting still pass. - Where CRAP stays below 5, a cognitive limit of 15 never fails, so it adds nothing there. It stays useful for code bases without a CRAP limit.
How to read CC, Cog, Cov% and CRAP together, and what to watch for in
an agent loop, is described in
docs/interpreting-scores.md. The sources
behind this section are collected in
docs/research/cognitive-complexity-and-crap-targets.md.
--cognitive-threshold [n] turns crap4dotnet into a quality gate
(ADR-0014). This is an intended departure from the reference tools, which
only report.
- Without the flag, nothing changes: the exit code is 0 when a report is produced.
- With the flag, every reported member (methods, constructors, local
functions, branching property accessors) is checked after module filters
are applied. A member fails when its cognitive complexity is greater
than
n; a score equal tonpasses, as in SonarQube's rule S3776. ndefaults to 15. If the argument after the flag is not an integer and does not start with-, crap4dotnet stops with a usage error; it never takes it as a module filter.nmust not be negative.- On failure the table is still printed and
.metrics/crap.jsonis still written. Then each failing member is listed on stderr, on a line that starts withgate:, with its score and location.
Exit codes:
| Code | Meaning |
|---|---|
| 0 | Report produced; gate passed or not enabled. |
| 1 | Error (bad arguments, missing or invalid baseline, missing coverage, project without coverage entry, failed coverage command). |
| 2 | Report produced, but a gate has at least one offender: a member above the cognitive threshold, or above the CRAP threshold (and new or worse than the baseline, if one is given). |
--crap-threshold [n] is the same kind of gate for the CRAP score
(ADR-0016). It is opt-in, n defaults to 30, and a member fails when its
CRAP score is greater than n. The value is parsed like the value of
--cognitive-threshold: an integer is the limit, no value or a following
option means the default, any other value is a usage error, and a negative
limit is rejected. The full report is written first. Then each offender is
listed on stderr on a gate: line with its score, the limit, and its file
and line. If both gates are on, the offenders of both are listed before the
exit code is decided.
With --baseline <path> the gate only fails for members that are new or
have a higher CRAP score than in an earlier .metrics/crap.json, and whose
score is above the limit. Old code that is above the limit may stay as it
is, but may not get worse. Members are matched by identity key
(namespace, type name and member name, ADR-0009). For overloads that share a
key, the worst score per key is compared. Members that no longer exist are
ignored. --baseline without --crap-threshold is a usage error, and a
missing or invalid baseline file is an error (both exit code 1).
A member without coverage data has no CRAP score. The CRAP gate skips it,
the table shows N/A, the JSON has coverage: null, and stderr ends with
gate: skipped <n> members without coverage data. A non-test project that
has no entry at all in the coverage report is an error (exit code 1), so a
failed coverage run cannot pass the gate.
Each entry in .metrics/crap.json has filePath (relative to the solution
root, with forward slashes) and line (start line), so overloads that share
an identity key can be told apart.
--output <path> replaces the report path, for example to write an "after"
report next to a committed baseline. --min-crap <n> hides entries with a
CRAP score below n in the table only; the report file and both gates
always see all entries. Below the table, a summary line shows the member
count. With --crap-threshold it also shows how many members are above the
limit and how many are offenders:
Members: 42, above CRAP limit 30: 3, offenders: 1
Code that Coverlet leaves out of the coverage report has no coverage data,
so the CRAP gate skips it and the count on stderr shows how many members
were skipped. Use [ExcludeFromCodeCoverage], or exclude by file or filter
in a runsettings file, for example:
<RunSettings>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="XPlat Code Coverage">
<Configuration>
<ExcludeByFile>**/Generated/*.cs</ExcludeByFile>
</Configuration>
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
</RunSettings>dotnet test --collect:"XPlat Code Coverage" does not load a
.runsettings file by itself. It was checked with .NET SDK 10.0 and
coverlet.collector 6.0.4: a .runsettings file in the project folder had
no effect, while --settings <file> and the MSBuild property
RunSettingsFilePath both applied the exclusion. The default coverage
command passes no settings, so pass the file with --coverage-command:
crap4dotnet --coverage-command 'dotnet test --collect:"XPlat Code Coverage" --settings coverage.runsettings'Alternatively, set <RunSettingsFilePath> in the test project or in
Directory.Build.props, so every dotnet test run uses the file.
An excluded member cannot be told apart from a member whose coverage was never collected, so review changes to the exclusion settings like code.
dotnet test # run unit + end-to-end tests
dotnet pack src/Crap4Dotnet.Cli -o nupkg # package the tool into nupkg/
dotnet tool restore # install the tool from nupkg/ (see .config/dotnet-tools.json)
dotnet tool run crap4dotnet # run against the current solutionnuget.config maps the package ID SincGmbH.Crap4Dotnet to the local nupkg/
folder only, so dotnet tool restore installs the build of this repo. Run
the dotnet pack command above before the first dotnet tool restore.
To contribute, read CONTRIBUTING.md and CODING_GUIDELINES.md. All participants follow the Code of Conduct.
See CLAUDE.md and docs/design-decisions.md for architecture and the
design decisions behind complexity counting, identity/overload handling,
and coverage parsing.
.claude/skills/crap4dotnet/SKILL.md — a project-scoped skill (mirroring
crap4clj's own SKILL.md) so Claude Code can run and interpret
crap4dotnet reports without re-deriving the CLI surface or CRAP-score
bands from scratch each session.
crap4dotnet started from Robert C. Martin's CRAP tools
(crap4clj,
crap4java,
crap4go) and contains no code from
them. It has since gone its own way, for example with cognitive complexity
and more command-line options. Where a design choice still matches those
tools on purpose, the ADRs in docs/adr/ say so.