dotnet-complexity
Use free built-in .NET maintainability analyzers and code metrics configuration to find overly complex methods and coupled code. Use when a repo needs cyclomatic complexity checks, maintainability thresholds, or complexity-driven refactoring gates.
Install
npx skills add https://github.com/Postpartum-genushyacinthus29/dotnet-skills/tree/main/skills/dotnet-complexity
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install postpartum-genushyacinthus29-dotnet-skills@llmmart
git clone https://github.com/Postpartum-genushyacinthus29/dotnet-skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole postpartum-genushyacinthus29/dotnet-skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
.NET Complexity Review
Trigger On
- the team wants to find overly complex methods
- cyclomatic complexity thresholds are needed in CI
- maintainability metrics or coupling thresholds need to be configured
Value
- produce a concrete project delta: code, docs, config, tests, CI, or review artifact
- reduce ambiguity through explicit planning, verification, and final validation skills
- leave reusable project context so future tasks are faster and safer
Do Not Use For
- formatting-only work
- generic analyzer setup with no complexity policy change
Inputs
- the nearest
AGENTS.md - current analyzer settings
- current maintainability limits
Quick Start
- Read the nearest
AGENTS.mdand confirm scope and constraints. - Run this skill's
Workflowthrough theRalph Loopuntil outcomes are acceptable. - Return the
Required Result Formatwith concrete artifacts and verification evidence.
Workflow
- Start with the built-in maintainability analyzers before reaching for non-standard tooling.
- Use these rules deliberately:
CA1502for excessive cyclomatic complexity in methodsCA1505for low maintainability indexCA1506for excessive class couplingCA1501when inheritance depth is also part of the design problem
- Keep rule severity in the root
.editorconfig. - Keep metric thresholds in a checked-in
CodeMetricsConfig.txtadded asAdditionalFiles. - Pair analyzer findings with MCAF maintainability limits in
AGENTS.md.
Bootstrap When Missing
If complexity thresholds are not configured yet:
- Detect current state:
rg -n "CA1501|CA1502|CA1505|CA1506|CodeMetricsConfig" -g '.editorconfig' -g '*.csproj' -g 'Directory.Build.*' .rg --files -g 'CodeMetricsConfig.txt'
- Add severity entries for
CA1502,CA1505,CA1506, andCA1501in root.editorconfig. - Add checked-in
CodeMetricsConfig.txtand include it asAdditionalFilesin project props. - Keep maintainability limits aligned with
AGENTS.md. - Run
dotnet build SOLUTION_OR_PROJECTand returnstatus: configuredorstatus: improved. - If policy relies only on
AGENTS.mdlimits with no analyzer gate by design, returnstatus: not_applicable.
Deliver
- explicit complexity and maintainability policy
- checked-in metric thresholds
- CI commands that surface complex methods early
Validate
- method-complexity checks are enabled where the repo wants them
- thresholds are versioned in repo, not held in IDE memory
- complexity findings map to real refactoring decisions
Ralph Loop
Use the Ralph Loop for every task, including docs, architecture, testing, and tooling work.
- Plan first (mandatory):
- analyze current state
- define target outcome, constraints, and risks
- write a detailed execution plan
- list final validation skills to run at the end, with order and reason
- Execute one planned step and produce a concrete delta.
- Review the result and capture findings with actionable next fixes.
- Apply fixes in small batches and rerun the relevant checks or review steps.
- Update the plan after each iteration.
- Repeat until outcomes are acceptable or only explicit exceptions remain.
- If a dependency is missing, bootstrap it or return
status: not_applicablewith explicit reason and fallback path.
Required Result Format
status:complete|clean|improved|configured|not_applicable|blockedplan: concise plan and current iteration stepactions_taken: concrete changes madevalidation_skills: final skills run, or skipped with reasonsverification: commands, checks, or review evidence summaryremaining: top unresolved items ornone
For setup-only requests with no execution, return status: configured and exact next commands.
Load References
references/complexity.mdreferences/metrics.mdreferences/config.md
Example Requests
- "Which analyzer finds complex methods in .NET?"
- "Add a complexity gate for our C# code."
- "Configure cyclomatic complexity thresholds."
Files (dotnet-skills)
-
references
-
complexity.md 2.3 KB
# .NET Complexity and Maintainability Rules ## Open/Free Status - first-party .NET analyzers - free to use with the .NET SDK ## Best Answer for Complex Methods If the question is "which analyzer finds methods that are too complex?", the primary built-in answer is: - `CA1502` for excessive cyclomatic complexity Closely related maintainability rules: - `CA1505` for low maintainability index - `CA1506` for excessive class coupling - `CA1501` for excessive inheritance depth ## Verify First Before adding anything, check whether the repo already configures these rules: ```bash rg -n "CA1501|CA1502|CA1505|CA1506|CodeMetricsConfig" -g '.editorconfig' -g '*.csproj' -g 'Directory.Build.*' . rg --files -g 'CodeMetricsConfig.txt' ``` ## Root .editorconfig Keep severity in the repo-root `.editorconfig`, for example: ```ini root = true [*.cs] dotnet_diagnostic.CA1502.severity = warning dotnet_diagnostic.CA1505.severity = warning dotnet_diagnostic.CA1506.severity = warning dotnet_diagnostic.CA1501.severity = suggestion ``` ## Threshold Configuration Thresholds for these code-metrics rules are configured through a checked-in `CodeMetricsConfig.txt` file, for example: ```text CA1502: 20 CA1502(Type): 6 CA1505: 10 CA1506: 30 CA1506(Type): 80 CA1501: 6 ``` Then include it in the project: ```xml <ItemGroup> <AdditionalFiles Include="CodeMetricsConfig.txt" /> </ItemGroup> ``` ## CI Fit - use `dotnet build` as the enforcement path - keep thresholds checked in - treat `CA1502` as the main answer for overly complex methods, not as a vanity metric ## When Not To Use - when the repo only wants stylistic linting and does not intend to act on maintainability findings ## Sources - [CA1502: Avoid excessive complexity](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1502) - [CA1505: Avoid unmaintainable code](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1505) - [CA1506: Avoid excessive class coupling](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1506) - [CA1501: Avoid excessive inheritance](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1501) - [Code metrics values](https://learn.microsoft.com/en-us/visualstudio/code-quality/code-metrics-values?view=vs-2022) -
config.md 5.4 KB
# Analyzer Configuration for Complexity Rules ## Configuration Layers Complexity analyzers can be configured at multiple levels: 1. **EditorConfig** - rule severity 2. **CodeMetricsConfig.txt** - numeric thresholds 3. **Project/Directory.Build.props** - analyzer package inclusion ## EditorConfig Setup ### Minimal Configuration Add to root `.editorconfig`: ```ini root = true [*.cs] dotnet_diagnostic.CA1502.severity = warning dotnet_diagnostic.CA1505.severity = warning dotnet_diagnostic.CA1506.severity = warning dotnet_diagnostic.CA1501.severity = suggestion ``` ### Severity Levels | Severity | Build Behavior | Use Case | |------------|------------------------------------|------------------------------------| | error | Fails the build | Hard enforcement in CI | | warning | Shows warning, build succeeds | Recommended default | | suggestion | Shows message in IDE only | Informational tracking | | silent | Runs but produces no diagnostics | Metric collection without noise | | none | Completely disabled | Intentionally ignored | ### Per-File Overrides To relax rules for generated or legacy code: ```ini [*.generated.cs] dotnet_diagnostic.CA1502.severity = none dotnet_diagnostic.CA1505.severity = none dotnet_diagnostic.CA1506.severity = none [**/Migrations/*.cs] dotnet_diagnostic.CA1502.severity = silent ``` ## CodeMetricsConfig.txt ### File Format The `CodeMetricsConfig.txt` file specifies numeric thresholds: ```text # Cyclomatic complexity per method CA1502: 20 # Cyclomatic complexity average per type CA1502(Type): 6 # Maintainability index minimum CA1505: 10 # Class coupling per method CA1506: 30 # Class coupling per type CA1506(Type): 80 # Inheritance depth maximum CA1501: 6 ``` ### Scope Suffixes | Suffix | Meaning | |--------------|----------------------------------------| | (none) | Per-method threshold | | `(Type)` | Per-type or type-average threshold | | `(Assembly)` | Assembly-wide threshold (where applicable) | ### Threshold Recommendations **Conservative (new projects):** ```text CA1502: 15 CA1502(Type): 5 CA1505: 20 CA1506: 20 CA1506(Type): 50 CA1501: 4 ``` **Moderate (established projects):** ```text CA1502: 20 CA1502(Type): 6 CA1505: 10 CA1506: 30 CA1506(Type): 80 CA1501: 6 ``` **Relaxed (legacy migration):** ```text CA1502: 30 CA1502(Type): 10 CA1505: 5 CA1506: 50 CA1506(Type): 120 CA1501: 8 ``` ## Project Integration ### Including CodeMetricsConfig.txt Add to `Directory.Build.props` for solution-wide application: ```xml <Project> <ItemGroup> <AdditionalFiles Include="$(MSBuildThisFileDirectory)CodeMetricsConfig.txt" Condition="Exists('$(MSBuildThisFileDirectory)CodeMetricsConfig.txt')" /> </ItemGroup> </Project> ``` Or add to individual `.csproj` files: ```xml <ItemGroup> <AdditionalFiles Include="../../CodeMetricsConfig.txt" /> </ItemGroup> ``` ### Analyzer Package Reference The maintainability rules require the .NET analyzers. For SDK-style projects targeting .NET 5+, these are included by default. For older projects or explicit inclusion: ```xml <PropertyGroup> <EnableNETAnalyzers>true</EnableNETAnalyzers> <AnalysisLevel>latest</AnalysisLevel> <AnalysisMode>Recommended</AnalysisMode> </PropertyGroup> ``` Or reference the package directly: ```xml <ItemGroup> <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="9.*"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference> </ItemGroup> ``` ## Suppression Strategies ### Attribute-Based Suppression For intentional violations: ```csharp [SuppressMessage("Maintainability", "CA1502:Avoid excessive complexity", Justification = "State machine requires explicit transitions")] public void ProcessState() { ... } ``` ### Global Suppressions Add to `GlobalSuppressions.cs`: ```csharp [assembly: SuppressMessage("Maintainability", "CA1506:Avoid excessive class coupling", Scope = "type", Target = "~T:MyNamespace.CompositionRoot", Justification = "Composition root is expected to have high coupling")] ``` ### Pragma Suppression For localized suppression: ```csharp #pragma warning disable CA1502 public void LegacyMethod() { // Complex legacy code pending refactoring } #pragma warning restore CA1502 ``` ## CI Integration ### Build Command ```bash dotnet build -warnaserror ``` ### Selective Error Promotion To fail only on complexity rules: ```xml <PropertyGroup> <WarningsAsErrors>CA1502;CA1505;CA1506</WarningsAsErrors> </PropertyGroup> ``` ### Baseline Workflow For existing codebases: 1. Set all rules to `suggestion` 2. Run `dotnet build` and capture baseline counts 3. Add `CodeMetricsConfig.txt` with current thresholds 4. Gradually tighten thresholds as code improves 5. Promote to `warning` when baseline is acceptable 6. Promote to `error` when enforcement is stable ## Sources - [Configure code analysis rules](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/configuration-options) - [EditorConfig settings](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/code-style-rule-options) - [Suppress code analysis warnings](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/suppress-warnings) -
metrics.md 4.1 KB
# .NET Code Complexity Metrics ## Overview .NET provides built-in code metrics through the Roslyn analyzers. These metrics quantify maintainability, complexity, and coupling without requiring third-party tools. ## Primary Metrics ### Cyclomatic Complexity (CA1502) Cyclomatic complexity measures the number of linearly independent paths through a method's source code. **Calculation:** - Start with 1 - Add 1 for each: `if`, `else if`, `case`, `while`, `for`, `foreach`, `&&`, `||`, `??`, `?.`, `catch`, conditional expression (`? :`) **Thresholds:** | Range | Risk Level | |---------|------------| | 1-10 | Low | | 11-20 | Moderate | | 21-50 | High | | 51+ | Very High | **Recommended default:** 20 for methods, 6 for type average. **Refactoring signals:** - Extract method for distinct logic branches - Replace conditional chains with polymorphism or strategy pattern - Simplify boolean expressions ### Maintainability Index (CA1505) The maintainability index is a composite metric ranging from 0 to 100 that indicates overall code maintainability. **Formula:** ``` MI = MAX(0, (171 - 5.2 * ln(HV) - 0.23 * CC - 16.2 * ln(LOC)) * 100 / 171) ``` Where: - HV = Halstead Volume (based on operators and operands) - CC = Cyclomatic Complexity - LOC = Lines of Code **Thresholds:** | Range | Maintainability | |---------|-----------------| | 20-100 | High | | 10-19 | Moderate | | 0-9 | Low | **Recommended default:** 10 minimum. **Refactoring signals:** - Large methods need decomposition - Complex expressions need simplification - Consider extracting classes for low-scoring types ### Class Coupling (CA1506) Class coupling counts the number of unique types that a type or method references, excluding primitives and common framework types. **What counts as coupling:** - Base types - Interface implementations - Parameter types - Local variable types - Method return types - Generic type arguments - Exception types **What is excluded:** - Primitive types (`int`, `string`, `bool`, etc.) - `System.Object` - `System.Void` **Thresholds:** | Scope | Recommended Maximum | |--------|---------------------| | Method | 30 | | Type | 80 | **Refactoring signals:** - Introduce abstractions to reduce direct dependencies - Apply dependency injection - Split large classes by responsibility ### Inheritance Depth (CA1501) Inheritance depth counts the number of types in the inheritance chain, starting from `System.Object`. **Thresholds:** | Depth | Risk Level | |-------|------------| | 1-4 | Low | | 5-6 | Moderate | | 7+ | High | **Recommended default:** 6 maximum. **Refactoring signals:** - Prefer composition over deep inheritance - Flatten hierarchies where intermediate classes add little value ## Metric Interactions These metrics often correlate: - High cyclomatic complexity typically lowers the maintainability index - High coupling often accompanies high complexity - Deep inheritance can mask complexity in base classes When multiple metrics flag the same code: 1. Address cyclomatic complexity first (most actionable) 2. Coupling improvements often follow complexity reduction 3. Maintainability index improves as other metrics improve ## Lines of Code Lines of code (LOC) is not enforced by a dedicated analyzer rule, but it factors into the maintainability index calculation. **Guidelines:** - Methods: prefer under 50 logical lines - Types: prefer under 500 logical lines - Files: prefer under 1000 logical lines ## Sources - [Code metrics values](https://learn.microsoft.com/en-us/visualstudio/code-quality/code-metrics-values) - [CA1502: Avoid excessive complexity](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1502) - [CA1505: Avoid unmaintainable code](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1505) - [CA1506: Avoid excessive class coupling](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1506) - [CA1501: Avoid excessive inheritance](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1501)
-
-
SKILL.md 4.4 KB
--- name: dotnet-complexity version: "1.0.0" category: "Metrics" description: "Use free built-in .NET maintainability analyzers and code metrics configuration to find overly complex methods and coupled code. Use when a repo needs cyclomatic complexity checks, maintainability thresholds, or complexity-driven refactoring gates." compatibility: "Requires a .NET SDK-based repository; respects the repo's `AGENTS.md` commands first." --- # .NET Complexity Review ## Trigger On - the team wants to find overly complex methods - cyclomatic complexity thresholds are needed in CI - maintainability metrics or coupling thresholds need to be configured ## Value - produce a concrete project delta: code, docs, config, tests, CI, or review artifact - reduce ambiguity through explicit planning, verification, and final validation skills - leave reusable project context so future tasks are faster and safer ## Do Not Use For - formatting-only work - generic analyzer setup with no complexity policy change ## Inputs - the nearest `AGENTS.md` - current analyzer settings - current maintainability limits ## Quick Start 1. Read the nearest `AGENTS.md` and confirm scope and constraints. 2. Run this skill's `Workflow` through the `Ralph Loop` until outcomes are acceptable. 3. Return the `Required Result Format` with concrete artifacts and verification evidence. ## Workflow 1. Start with the built-in maintainability analyzers before reaching for non-standard tooling. 2. Use these rules deliberately: - `CA1502` for excessive cyclomatic complexity in methods - `CA1505` for low maintainability index - `CA1506` for excessive class coupling - `CA1501` when inheritance depth is also part of the design problem 3. Keep rule severity in the root `.editorconfig`. 4. Keep metric thresholds in a checked-in `CodeMetricsConfig.txt` added as `AdditionalFiles`. 5. Pair analyzer findings with MCAF maintainability limits in `AGENTS.md`. ## Bootstrap When Missing If complexity thresholds are not configured yet: 1. Detect current state: - `rg -n "CA1501|CA1502|CA1505|CA1506|CodeMetricsConfig" -g '.editorconfig' -g '*.csproj' -g 'Directory.Build.*' .` - `rg --files -g 'CodeMetricsConfig.txt'` 2. Add severity entries for `CA1502`, `CA1505`, `CA1506`, and `CA1501` in root `.editorconfig`. 3. Add checked-in `CodeMetricsConfig.txt` and include it as `AdditionalFiles` in project props. 4. Keep maintainability limits aligned with `AGENTS.md`. 5. Run `dotnet build SOLUTION_OR_PROJECT` and return `status: configured` or `status: improved`. 6. If policy relies only on `AGENTS.md` limits with no analyzer gate by design, return `status: not_applicable`. ## Deliver - explicit complexity and maintainability policy - checked-in metric thresholds - CI commands that surface complex methods early ## Validate - method-complexity checks are enabled where the repo wants them - thresholds are versioned in repo, not held in IDE memory - complexity findings map to real refactoring decisions ## Ralph Loop Use the Ralph Loop for every task, including docs, architecture, testing, and tooling work. 1. Plan first (mandatory): - analyze current state - define target outcome, constraints, and risks - write a detailed execution plan - list final validation skills to run at the end, with order and reason 2. Execute one planned step and produce a concrete delta. 3. Review the result and capture findings with actionable next fixes. 4. Apply fixes in small batches and rerun the relevant checks or review steps. 5. Update the plan after each iteration. 6. Repeat until outcomes are acceptable or only explicit exceptions remain. 7. If a dependency is missing, bootstrap it or return `status: not_applicable` with explicit reason and fallback path. ### Required Result Format - `status`: `complete` | `clean` | `improved` | `configured` | `not_applicable` | `blocked` - `plan`: concise plan and current iteration step - `actions_taken`: concrete changes made - `validation_skills`: final skills run, or skipped with reasons - `verification`: commands, checks, or review evidence summary - `remaining`: top unresolved items or `none` For setup-only requests with no execution, return `status: configured` and exact next commands. ## Load References - `references/complexity.md` - `references/metrics.md` - `references/config.md` ## Example Requests - "Which analyzer finds complex methods in .NET?" - "Add a complexity gate for our C# code." - "Configure cyclomatic complexity thresholds."
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.