Applying consistent code styles with Visual Studio 2017
[Visual Studio 2017](https://www.visualstudio.com/" target="_blank) offers an extended set of tools that can help developers be more productive and for teams to be more cohesive and consistent. Code consistency is importan at any level you look at it: individual, team and enterprise. Although each developer has his/her unique code writing style, there are cases where we may want to apply a consistent set of rules/styles across a project or event an entire development team.
In the past, the best way to do this was through code analysers such as [FxCop](https://blogs.msdn.microsoft.com/codeanalysis/tag/fxcop/" target="_blank) or [StyleCop](https://github.com/StyleCop/StyleCop" target="_blank). They came with a large list of rules that could be applied at build time and, depending on the configured severity break the build, for any broken rules. I'm sure many of you have had their fair share of "joy" battling with rigid or annoying rules to the point that… let's just say that in some cases it made for some interesting watercooler conversations.
FxCop and StyleCop are still alive and kicking today, albeit a lot more improved and transformed to work with Roslyn. Instead of the "old-way" of having to install the extensions and run an extra step during build to validate the rules, we now get immediate feedback inside the IDE thanks to Roslyn. Roslyn runs constantly these rules quietly, in the background making for a much better experience. The other big improvement is that these analysers now come in the form of NuGet packages which makes installing and uninstalling them a breeze. No more extensions! An overall improved experience.
But what if you didn't want to use the extensive list of FxCop or StyleCop? Even the "cop" in the name makes them sound ominous. VS2017 has an answer for this in the form of 2 new options:
- Code Style in VS2017
- EditorConfig
Using the Code Styles settings in VS2017
The Code Style in VS2017 is a configuration option that applies to all projects and is configured in the IDE. This means that once it's set up, all projects will get the same "treatment". There is still no need to install an extension, although the limited scope (IDE only) makes it less appealing for larger teams. To set up the rules, you need to go into Tools -> Options -> Text Editor -> Code Style (C# or VB)
Next, we can go through each rule and define what the default action/setting should be and how to treat non-conforming code. For example, picking a rather sensitive subject to demonstrate this, var
vs explicit parameter
declarations, I want to ensure that the IDE promotes explicit declarations (i.e int, string, bool etc). In real life, I prefer the opposite but stay with me here. I have a point to prove. The picture below shows how to set this up
If we go back to my very "sophisticated" code, you can see that the IDE is now highlighting this as an error.
But is it really an error? Unfortunately, although the IDE is giving us all the visual cues that we need to go and fix the highlighted errors, the build process says otherwise. Kicking off a build (Ctrl+Shift+B) results in no errors. In effect, as nice as this feature is, it's only noise that could easily be ignored (if you can live with yourself, of course).
Another issue with this option is that any code syntax errors identified based on our rules are only applicable locally and the CI/CD tools are totally oblivious to these settings. This is not an enforceable policy that teams can adopt to provide code consistency but rather a nice-to have feature. In the end, I cant see myself recommending this as a viable option. Which leads us to option 2
Using the EditorConfig project for code consistency
I truly applaud the Visual Studio team's initiative to bring Open Source tooling (even more OSS tooling) to VS2017 in order to implement this feature. Unlike the previous, IDE-only feature, the use of [Editorconfig](http://editorconfig.org" target="_blank) files is not a VS-only or even a Microsoft thing. It's an open source tool that:
"helps developers define and maintain consistent coding styles between different editors and IDEs"
How awesome is this? If you use Node, Python, .NET (Core), Go, HTML, CSS etc, you can apply consistent, IDE-independent styling with minimal effort. Visual Studio 2017 also adopted this approach so now you can take full advantage of this feature to enable source-controlled coding styles at any level you wish (project, machine, organisation). The EditorConfig project uses a text based approach for defining the coding styles and then it's down to each IDE to enforce these rules. Each code editor needs to implement a plugin that enables the editor to read the file format and adhere to defined styles.
Summarizing what we learned so far, the EditorConfig project is open source, it's maintained by the community, it's IDE agnostic can be used with many languages. So far so good. Let's see how to use it inside VS2017 to apply coding styles.
Although in principle, the EditorConfig project sounds like a great idea, there were a few issues when using it as is with .NET projects. That's because the rule format doesn't work out-of-the box. To fix this, the VS team worked closely with the EditorConfig community to make things work.
So unlike the usual rule format: {style:value} e.g.
[*]
end_of_line = lf
insert_final_newline = true
The .NET rule format has been extended to help provide the necessary visual queues inside VS2017. The extended style format is:{ rulename:value:severity} e.g.
dotnet_style_qualification_for_field = false:suggestion
This allows VS2017 to highlight any issues and according to the severity list the item under the appropriate category:
- Error
- Warning
- Message
One of the best [.editorconfig samples](https://github.com/dotnet/roslyn/blob/master/.editorconfig" target="_blank) can be found at that Roslyn Github repo. To use this with your code, just drop it at the root of your project.
Applying a specific style
In true inflammatory manner and knowing pretty well that I can start a holy war I'll use the Tabs vs Spaces style. If you're too young or have no idea what I'm talking about, the following video from the Silicon Valley TV show is spot on:
Open up the EditorConfig file in Visual Studio and change the following setting value from space to tab and save the changes (I also love the comment saying to explicitly NOT use tabs):
#Don't use tabs for indentation.
[*]
indent_style = tab
You may notice is that although we changed the .editorconfig
file, the new style is not applied to the open files. To enforce the new code styles, you need to close and reopen any open files in the IDE. New code added will automatically get the new styles applied to it. For any existing code, you'll need to either "Format Document" using Ctrl+E,D or go to highlight all the code and then go to Menu -> Edit -> Advanced -> Format Document. Another thing to note is that if you use both the VS2017 Code Style settings and EditorConfig, then the EditorConfig style rules will overwrite/preceed those in the Tools -> Settings
In the following example I show you how to apply the new tabs-all-over-the-place style (i.e change to Tabs)
Another nice touch when using the EditorConfig styles is the subtle message you get in the notification bar to let you know that .editorconfig
styles are into effect in this project:
The good bits
- No need to mess with NuGet packages
- You can source control the changes
- Works across multiple IDEs
- Conforms with open source standards
- You can have a "root" EditorConfig that applies to all projects instead of a per-project EditorConfig style. Or you can mix and match
The bad bits
- Although errors and warnings turn up in the Error Tab in the IDE, the build doesn’t break
- VSTS doesn't understand and can't break the build on EditorConfig errors
The future of Code Styles
You may think that the whole point of this post is moot considering that neither approach is truly enforceable at build-time. To that I say: NOT YET! The VS team is hard at work to make these rules enforceable to ensure that your code abides to your standards. In the meantime, there's nothing stopping you from adopting the EditorConfig tooling to bring that extra bit of goodness and productivity to your team.
Make sure you communicate your intentions with the rest of the team and reach a consensus about which rules make sense. It needs to be a collective decision for everyone to buy into this feature
Give it a go today and make sure to let the VS team how much you love this feature