Search Sreeni's Insights

Filter by content type
crafting November 15, 2016 7 min read

Static code analysis with StyleCop, FxCop and ReSharper

Static code analysis explained through StyleCop, FxCop, ReSharper, rule sets, IDE checks, local builds, CI integration and gradual warning reduction.

Share:

Static code analysis with StyleCop, FxCop and ReSharper

Code reviews are one of the best practices we have, but they are expensive. When the reviewer spends half of the time commenting on brace positions, missing using order, unused variables and naming, there is not much energy left for the things only a human can review, the design, the business logic and the edge cases. And also, two reviewers rarely comment on the same things, so the code style is depending on who reviewed it. These checks are boring for humans but very easy for tools.

In the previous article, we discussed Git branching strategies and the pull request workflow. In this article, we are going to see what is static code analysis, the tools available for .NET teams, StyleCop, FxCop (Visual Studio Code Analysis) and ReSharper, and how we introduced them into our development and build process without stopping the teams.

TL;DR Summary

  • Static code analysis checks the source code or compiled assemblies without running them.
  • StyleCop checks the style and consistency of C# source code (layout, naming, ordering, documentation).
  • FxCop / Visual Studio Code Analysis checks the compiled code for design, security, performance and correctness issues.
  • ReSharper gives the analysis inside the IDE while typing, and its command line tools can run in the build.
  • Run the analysis at three places, IDE, local build and CI build, the earlier the cheaper.
  • Share one rule set across all projects, start with a small set and add more over the time.
  • On existing code, don’t fail the build on day one, fix the new code first and reduce the warnings gradually.

Challenges

Inconsistent code

Every developer has a personal style. In a codebase touched by 20 developers over five years, we have five ways to name private fields and three ways to order the members. It makes the code harder to read and every file looks like a different project.

Review fatigue

When the reviewers are commenting on style, the pull requests are taking longer and the comments feel personal. The real issues like a missing Dispose or a SQL injection risk are getting missed between the style comments.

Known bugs repeated

Some bugs are very common and well known, not disposing a SqlConnection, catching a general Exception, string comparison without culture, async void methods. Humans miss them, tools don’t.

What is Static code analysis?

Static code analysis is the automated examination of source code or compiled code, without executing it, against a set of rules to find defects, security weaknesses, maintainability issues and style violations.

In simple terms, it is a spell checker and grammar checker for our code. It cannot tell us if the story is good, that is still the reviewer’s job, but it catches the spelling mistakes before anyone reads it.

The tools

StyleCop

StyleCop analyses C# source code and enforces a set of style and consistency rules, like ordering of members, spacing, naming, using directives and documentation headers. There are two flavours today,

  • StyleCop (classic) - a Visual Studio extension and MSBuild integration.
  • StyleCop.Analyzers - the new Roslyn based analyzers, installed as a NuGet package. It works with Visual Studio 2015, shows the warnings while typing and runs in every build without any extra setup.

For new projects, we use StyleCop.Analyzers, because the rules travel with the project and work on the build server the same way as on the developer machine.

FxCop / Visual Studio Code Analysis

FxCop analyses the compiled assemblies (IL) against the .NET Framework Design Guidelines. In Visual Studio, it is available as Code Analysis (Project Properties → Code Analysis), with rule sets like “Microsoft Minimum Recommended Rules” and “Microsoft All Rules”. It finds issues like,

  • CA2000 - Dispose objects before losing scope.
  • CA1062 - Validate arguments of public methods.
  • CA2100 - Review SQL queries for security vulnerabilities.
  • CA1031 - Do not catch general exception types.

ReSharper

ReSharper is a commercial Visual Studio extension by JetBrains. It gives code inspections, quick fixes and refactorings while typing. The inspection settings can be saved in a team shared settings file (.DotSettings) and committed with the solution. JetBrains also provides free command line tools, InspectCode and dupFinder, which can run the same inspections in the build server.

ToolAnalysesWhere it runsStrength
StyleCop.AnalyzersSource codeIDE + every buildConsistent style, zero setup on build server
FxCop / Code AnalysisCompiled assemblyBuildDesign, security and correctness rules
ReSharperSource codeIDE (+ CLI tools in build)Real-time feedback and quick fixes

Why Static code analysis is important?

In order to keep the codebase consistent, to catch the well known defects before the code review and to let the reviewers focus on the design and business logic, static code analysis must be part of our process. It also helps the new joiners, they learn the team’s conventions from the tool, not from 30 review comments on their first pull request.

Where to run the analysis?

The following diagram depicts the stages where we run the static code analysis.

Static code analysis stages
Static code analysis stages

The stage highlighted in purple is the CI build on VSTS. It is the gate, if the analysis fails, the pull request cannot be merged. The IDE and local build stages give the developer an early feedback, so most of the issues never reach the CI build.

Steps to Implement:

Follow the following instructions to set up the analysis for a solution.

  • Install StyleCop.Analyzers to every C# project.

    Install-Package StyleCop.Analyzers
  • Create a shared rule set file Team.ruleset at the solution root, start from “Microsoft Minimum Recommended Rules” and adjust the StyleCop rules which your team doesn’t want (ex: SA1633 file header, if you don’t use file headers).

  • Reference the rule set and enable Code Analysis in every .csproj.

    <PropertyGroup>
      <CodeAnalysisRuleSet>..\Team.ruleset</CodeAnalysisRuleSet>
      <RunCodeAnalysis>true</RunCodeAnalysis>
    </PropertyGroup>
  • Add a stylecop.json file for the settings like company name and using directive placement, and link it to all projects as AdditionalFiles.

  • Save the ReSharper team settings as “Solution team-shared” so the .sln.DotSettings file is committed with the solution.

  • In the VSTS build definition, enable “Treat warnings as errors” for the release configuration, or pass it to MSBuild.

    msbuild FundPlatform.sln /p:Configuration=Release /p:TreatWarningsAsErrors=true
  • Optionally, run ReSharper InspectCode in the build and publish the report as an artifact.

    inspectcode.exe FundPlatform.sln --output=inspectcode-report.xml
  • Just to pulse check, introduce a small violation (ex: an unused private field) in a branch and make sure the pull request build fails.

Note: For a quick start, Visual Studio’s built-in rule sets are fine, but for production codebases, it is highly recommended to agree a team rule set and version it in source control, otherwise every project ends up with different rules.

Introducing it to existing code

When we enabled all rules on our oldest solution, we got <N> warnings [confirm: real count]. Failing the build on day one was not an option. Here is how we approached it,

  1. Started with a small rule set with the important rules only (security, dispose, exception handling).
  2. Enabled “Treat warnings as errors” for new projects only.
  3. Followed the boy scout rule, every file touched in a pull request must have zero warnings.
  4. Tracked the warning count per build and reduced it every sprint.
  5. Added more rules once the count was close to zero.

Must Do and Don’ts

  • Must Do: Use one shared rule set for all projects in the solution.
  • Must Do: Run the analysis in the CI build, not only in the IDE.
  • Must Do: Document why a rule is suppressed, with a justification in SuppressMessage.
  • Should: Fix the root cause instead of suppressing the warning.
  • Don’t: enable all rules at once on a legacy codebase.
  • Don’t: argue about style in code reviews, change the rule set instead.

Wrap up

In this article, we have looked at the challenges of manual style reviews, what is static code analysis, StyleCop, FxCop and ReSharper, where to run them and how to introduce them to existing code. I really appreciate that you took the time to read this article. In the next article, I will walk you through TypeScript for C# developers, Part 1.

Related Posts