How to Improve Code Quality by Enforcing a consistent Coding Style across projects?
It is very hard! Code style rules could become hard to maintain easily, speaking from a personal experience.
In AVS Solutions, we are using external tools to help us, but in the end, for some code style rules, there is no library or help from an outsider. Depending on the language and type of the project, we use different static code analyzers to enforce the rules. They are beneficial, but they have certain limitations.
Recently, the team agreed on a rule of passing pass inner exception when an exception is thrown from a catch clause. At this time, I will not go into further details as to why this is good practice. During the first couple of pull requests created, we successfully detected and enforced the rule. Over time the rule went under our radar, so few code changes got missed.
AVS tool to help detect all locations where the rule is not applied
Our next decision was to make a tool to help detect all locations where this rule wasn’t applied yet.
For this, we resorted to our team resources and made a tool for analyzing our code and avoiding repeating the same mistakes.
After some reading, we decided to use Roslyn, so we created the new rule in a couple of hours. We made three unit tests to secure implementation:
- Rethrow should not be an error
- Catch and throw without inner exception argument is an error
- Catch and throw with the inner exception that is not caught in the catch clause is an error
A new NuGet package was made and released to the NuGet repository for all team members to use in the project. Immediately after we included the package in the solution, we got all the errors in the build time. We fixed the errors, and a new pull request was on the way.
From now on, this style rule will give an error in build time in any solutions where we include it. All AVS Solutions team members will know about it, so no longer there will be a need for comments like “Please pass inner exception”.