Ensuring everyone has the same conventions is important; it helps to keep all the code looking like it was developed with one mind. But doing so is a lot of work. I don’t know how many pull request comments I have seen along the lines of “this should be Pascal Case, not Camel Case”. Way too many.
And doing static code analysis is something humans are not great at, but computers are. So why not just have the computer perform the static analysis?
Here’s a way to do it, although I should note that it’s not perfect (but it’s a start).
To get started, you need an EditorConfig file (.editorconfig). Some IDEs will actually generate this file for you, but there are also a variety of these files out there on the internet. For example, this web page contains an example of what an EditorConfig file looks like for C#.
Once you have an EditorConfig file, your IDE might already show violations of these rules to you. But if not, you can run these rules using the dotnet formattool from the command line to see these issues.
To run from the command line, you will first need to install the dotnet format tool.
dotnet tool install -g dotnet-format --version 5.0.135301 --add-source https://dotnet.myget.org/F/format/api/v3/index.json'
Run the following command to run the tool:
dotnet format --fix-syle --check
The above command will probably produce some errors like these:
AuthenticationTests.cs(54,17): Unnecessary assignment of a value to 'guid' Program.cs(25,42): Remove unused parameter 'args' if it is not part of a shipped public API ManagerBase.cs(26,28): Remove unused parameter 'count' if it is not part of a shipped public API MissionControlManagerTests.cs(36,17): Unnecessary assignment of a value to 'savedClient'
Doing that will give you potentially a bunch of errors to go and fix. Easy things such as tabbing / spacing can be fixed by the format tool itself. You can just run it and let it fix those with the following command.
Since this is all automatable from the command line, you can even run this as part of your build process. You just need to add these steps to your yaml file.
- task: DotNetCoreCLI@2 inputs: command: 'custom' custom: 'tool' arguments: install -g dotnet-format --version 5.0.135301 --add-source https://dotnet.myget.org/F/format/api/v3/index.json - task: DotNetCoreCLI@2 inputs: command: 'custom' custom: 'format' arguments: '--fix-style --check' workingDirectory: 'path/to/project'
While this seems great, I have found it somewhat lacking. For example, getting it to show naming rule errors hasn’t really worked out for me, but I think that is probably because we’re still in the early days of these tools. Eventually, this could be a great way to ensure code standards without requiring humans to do the audits.