How to enforce a consistent coding style in your projects

 
 
  • Gérald Barré

This post is part of the series 'Coding style'. Be sure to check out the rest of the blog posts of the series!

Every company/team has its coding style. The coding style is about naming, spacing, or language feature usages. Do you use tabs or spaces, and how many spaces? Do you use PascalCase or camelCase? Do you prefix field names with _? Do you always use var or only when the type is visible? And a few more questions in that vein…

In an open/inner source project, you want to ensure every contributor uses your coding style so your codebase remains consistent. It also reduces the number of comments in code review just for adding some spaces, or small things.

Let's see which tools are available to ensure contributors use your coding style!

#.editorconfig file

Here's the introduction from editorconfig.org:

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs. The EditorConfig project consists of a file format for defining coding styles and a collection of text editor plugins that enable editors to read the file format and adhere to defined styles. EditorConfig files are easily readable and they work nicely with version control systems.

EditorConfig is supported by Visual Studio natively and Visual Studio Code via a plugin (download). Lots of other IDE support it natively or using a plugin, including JetBrains Rider.

##How does it work?

The IDE looks for a file named .editorconfig at the root of your repository. This file contains instructions for different files based on a globing pattern. You have global instructions like indent_style or indent_size, and C# specific instructions like dotnet_sort_system_directives_first.

The .editorconfig file is in the repository, so every contributor can use it to write a code that matches the coding style. Also, Visual Studio will show quick fixes to change your code to match the coding style defined in the configuration file.

Here's an example:

INI
[*]
indent_style = space

[*.{cs,csx,vb,vbx}]]
indent_size = 4
insert_final_newline = true
charset = utf-8-bom

[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2

[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2

[*.{cs,vb}]
# Sort using and Import directives with System.* appearing first
dotnet_sort_system_directives_first = true
dotnet_style_require_accessibility_modifiers = always:warning

# Avoid "this." and "Me." if not necessary
dotnet_style_qualification_for_field = false:warning
dotnet_style_qualification_for_property = false:warning
dotnet_style_qualification_for_method = false:warning
dotnet_style_qualification_for_event = false:warning

# ...

Here are some useful resources about editor config for .NET:

Build errors in Visual StudioBuild errors in Visual Studio

Quick Fixes using the quick action menuQuick Fixes using the quick action menu

You can format your existing code to follow the rules set in the .editorconfig file using the global tool dotnet-format:

Shell
dotnet tool install -g dotnet-format

Then, you can use dotnet format in a folder that contains your solution

Shell
cd c:\sources\my-project
dotnet format

Diff before and after running dotnet formatDiff before and after running dotnet format

#Linters / Roslyn Analyzers

Another useful tool to ensure a consistent coding style is to use a linter. A linter is a tool that runs on your codebase and ensures it doesn't violate some rules. A linter often includes some best practices rules in addition to formatting rules. For instance, it can detect incorrect usage of an API. If you are familiar with async/await it can detect missing awaits. In c# you can use StyleCop. If you use TypeScript, you can use tslint. There are linters for almost all languages.

Here's an error detected by tslint:

tslint outputtslint output

You can check my other post about tslint for more information.

Roslyn analyzers act like a linter, except it's fully integrated into the build pipeline and the IDE and may come with refactoring to automatically fix issues. There are plenty of existing analyzers. Check the store to find useful analyzers. I also have a nice list of Visual Studio extensions in this post.

Roslyn analyzerRoslyn analyzer

#Visual Studio Code configuration

Visual Studio Code has a settings file that contains lots of options to format documents. It can contain settings for all languages and also per language. Create a file .vscode\settings.json, and set the values you want to share with your team.

JSON
{
  // Global settings
  "files.insertFinalNewline": false,
  "files.trimFinalNewlines": false,
  "files.trimTrailingWhitespace": false,

  // Per language settings
  "javascript.format.enable": true,
  "javascript.format.insertSpaceAfterCommaDelimiter": true,
  "javascript.format.insertSpaceAfterConstructor": false,
  "javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": true,
  "javascript.format.insertSpaceAfterKeywordsInControlFlowStatements": true,
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces": false,
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": true,
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": false,
  "javascript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis": false,

  "[git-commit]":  {
    "editor.rulers": [72]
  },

  // ...
}

The full list of settings is available in the documentation: Visual Studio Code - Default Settings

#Resharper / Rider

I don't use Resharper nor Rider (the JetBrains .NET IDE), but many people do. Resharper comes with a set of formatting options. You can save this configuration in a file in your repository. This way everyone that uses Resharper with your repository will use the shared settings. It's like a .editorconfig but for Resharper. Also, Resharper read some information from the .editorconfig, so having both can be useful in the case where not every contributor use Resharper.

Resharper code formatting optionsResharper code formatting options

You can use Resharper CLI (free) to clean up your code. It's a command-line tool that reads the configuration files and reformats all documents in your solution.

Here's some information from the documentation of Resharper:

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub