Improving Code Quality - Code Analysis

To turn this on, go to Analyze > Configure Code Analysis > For Solution

In the following pop-up window, ensure that you have selected “All Configurations” under the Configuration option. This will make any changes you make in the dialog box to all the configurations for your application.

You can pick from a number of different rulesets – if you’re feeling brave, go for All Rules as something to strive for! You can now manually run the Code Analysis by heading back to Analyze > Run Code Analysis > On Solution

This will then show you any Code Analysis rules that are currently being broken by your code:

Note that each code is hyperlinked – click this to view a description of the rule, understand the reason for it, and what you need to do to comply with it. I had 684 violations which isn’t great, but I have a very clear picture of where I can improve my code. There are some rules that I want to ignore because I have my own rules I am following – for example namespace casing – I use all capitals for the initials of the owning company where Microsoft want me to use Camel Casing. To do this, simply right click on the violation you want to suppress, and choose suppress, then either in source or in suppression file. Sometimes the suppression has to be stored in the suppression file as it can’t be added to source. Both have advantages – the suppression file keeps it all in one place, but having it inline in code means you can see at a glance any suppressed rules when working on that code.

Rather than trying to fix everything at once, simply set yourself a rule that you will only ever have an equal or lesser number of rule validations. This way you can slowly improve your compliance over time without it impacting your work velocity.

Finally, you can get the Code Analysis to run every time you build (and every time an automated build runs). For each project in your solution, Right click on it and go to Properties > Code Analysis. Choose “All Configurations” from the Configuration options, and the check “Enable Code Analysis on Build”. This will slow down your build, however it will keep you aware of where you are sitting with the Code Analysis rules.

Next: Implementing Unit Tests

Tagged: Code Quality, Visual Studio, .Net,
Categorised: Application Lifecycle Management,