How to enforce a consistent coding style in your projects

Every company/team has its own 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 look for a file named .editorconfig at the root of your repository. This files contains instructions for different files based on a globbing 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 match 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:

[*]
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's some useful resources about editor config for dotnet:

Build errors

Quick Fixes

Linters / Roslyn Analysers

Another useful tool to ensure a consistent coding style is to use a linter. A linter is a tool that run on your code base and ensure it doesn't violate some rules. A linter often include 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. And there are linters for almost all languages.

Here's an error detected by tslint:

tslint output

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

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

Roslyn analyser

Visual Studio Code configuration

Visual Studio Code has a settings file that contains lots of options to format documents. It can contains 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.

{
  # 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

I don't use Resharper, 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 an .editorconfig but for Resharper. Also, Resharper read some informations from the .editorconfig, so having both can be useful in the case not every contributor use Resharper.

Here's some information from the documentation of Resharper: