Tag Archives: Code Analysis

Seven Steps to Quality Code – Step 5

Code Analysis – Further Rules

This is step 5 in a series of articles, starting with Seven Steps To Quality Code – Introduction.

This step is simply a case of turning the ratchet a little more and locking in further quality gains.

Previously, my suggestion for existing projects has been to set the Code Analysis rule set to “Minimum recommended rules” (or in Visual Studio versions after 2010, “Managed Recommended Rules”) in order to keep the number of rule violations to a minimum.  Now I am going to suggest that the rules are tightened by using a rule set or combination of rule sets that check for further violations.

Ultimately, our goal is to have the “All Rules” rule set enabled on all code, but in practice this may not be achievable for legacy code.  What we can do, is work towards this so that we can catch the more important issues in our code.  For example, the effort of implementing the globalisation rules in legacy code is not going to give you much bang for buck (unless of course globalisation has become a required feature!).

A great feature of Code Analysis is that we can progressively add further rules in order to increase the range of issues that are checked.  The rule sets that are available, however, do not give us a sequential order that we can progressively move through because particular rule sets focus on particular issues.  We can achieve the same effect though by using the option of progressively applying multiple rule sets.  You can do this by selecting the “Choose multiple rule sets” option on the Code Analysis tab of a project’s properties screen, as shown in the screenshot below:

Screenshot showing where to select multiple Code Analysis rule sets
Selecting the Multiple Rule Sets Option

A comprehensive list of the rule sets available can be found on the Microsoft site:

Visual Studio 2010 Code Analysis Rule Sets
Visual Studio 2013 Code Analysis Rule Sets

To avoid getting swamped by too many violations and to allow a “small bite at a time” approach, I suggest considering 1 project (i.e. csproj file) at a time and performing the following procedure:

  1. Run the “All Rules” rule set on the project.  If you consider the number of violations to be manageable, use the “All Rules” rule set.  This is the perfect situation to be in, ignore the further steps in this list and proceed to fix the violations.
  2. If “All Rules” is looking like a step too far, progressively add in the following rule sets one at at time, fixing the violations and checking in as you go:
    Visual Studio 2010Visual Studio 2013
    Microsoft Basic Correctness RulesBasic Correctness Rules rule set for managed code
    Microsoft Basic Design Guideline RulesBasic Design Guideline Rules rule set for managed code
    Microsoft Extended Correctness RulesExtended Correctness Rules rule set for managed code
    Microsoft Extended Design Guideline RulesExtended Design Guidelines Rules rule set for managed code
  3. At this point, you may be in a position to apply the “All Rules” rule set and have a manageable number of violations.  Alternatively, if that still produces too many violations, you may have a particular need for one of the remaining focused rule sets (security or globalization rules) and wish to apply one of those. (Actually, by the time you get to this stage the likelihood is that if you have a lot of violations under “All Rules” they will all be globalization related).

Conclusion

Once this step is followed for a solution, you will be in a great place for continuing development in a high quality environment with automatic guards in place to keep it there.

In step 6 we’ll look at peer reviews – something that everyone knows about but all too often they are the easiest thing to discard in a development process.

Seven Steps to Quality Code – Step 3

Code Analysis – Minimum Rules

This is step 3 in a series of articles, starting with Seven Steps To Quality Code – Introduction.

In this step, things are going to start getting interesting. Up to now, the incremental changes that we have made are fairly non-disruptive – remove some unused variables here, add some XML comments there – not things that are likely to break your existing code (not too much anyway!). This is where we (gently) introduce Code Analysis and start to weed out bugs and refactor the code.

Code Analysis is a feature built in to certain editions of Visual Studio.  It will, as its name suggests, analyse your code to detect bad practices, anti-patterns and outright bugs.  It does this by validating the code against a predetermined set of rules and reporting violations as warnings in the Error window within Visual Studio.

Originally, this tool used to be available as part of the Windows SDKs (Software Development Kits) from Microsoft.  It was called “FxCop” and was a tool that was created to help developers, initially within Microsoft, to build more robust and maintainable code that followed the Microsoft Design Guidelines.  If you aren’t lucky enough to be using one of the Visual Studio versions with Code Analysis built-in, then you can download the program in its original “FxCop” guise from here.  The interaction with the tool is different, but the underlying system is the same.  For the purposes of this article, I’ll be using screenshots and instructions for the built-in Code Analysis.

Now let’s get started.  Firstly, to switch on Code Analysis for a solution got to Analyze on the Visual Studio main menu, and select Configure Code Analysis for Solution.

Visual Studio's Analyze Menu

In the dialog that is then displayed, select “All Configurations” in the Configuration dropdown and ensure that the projects on which we want to run Code Analysis are set to “Microsoft Minimum Recommended Rules”, as shown below.

Property Pages for a Solution

You may see that in the dropdown, there are several “Rulesets” to choose from. These are subsets of the whole set of rules, allowing various levels of compliance to be easily selected. My approach is that we start with the “Microsoft Minimum Recommended Rules” because it contains the most important rules, violations of which are more likely to generate bugs than the rules included in the more complete rulesets.

Next, right click each project in Solution Explorer and Select “Properties” to get the Project Properties screen and then select the Code Analysis tab. Here, you should ensure that “All Configurations” is selected in the Configuration dropdown and check the “Enable Code Analysis on Build” checkbox, as shown below. This will need to be carried out for each project in the solution.

Properties for a Project - Code Analysis tab

The above step isn’t absolutely necessary, but it means that you or your developers don’t have to remember to run the analysis, Visual Studio will do it for them each time the solution is built. We want to make this whole task integrate completely into the development process and checking this option goes a long way to achieving that.

The next thing to do is simply to build your solution and observe the warnings that are produced.

If you are running this on an existing project, the chances are you will get very many warnings. Don’t be alarmed! A lot of them will be easy to fix and each one fixed means that your code is taking a further step towards the robust and maintainable code that you would like to see.

To help you fix each rule violation, there is excellent documentation available on MSDN. This can easily be accessed by right-clicking a particular warning and selecting “Show Error Help”. This is a fntastic training aid, frequently reading the error help will improve developer knowledge dramatically. This is like having a true .Net guru reviewing the code and providing exact details on how issues should be addressed.

If a rule violation should be allowed in your project for some reason, the warning can be suppressed by right-clicking and selecting “Suppress Messages” then “In Source” or “In Project Suppression File”.  This will add an attribute into your code (either at the site of the violation if “In Source” was selected, or in a GlobalSuppressions.cs file if “In Project Suppression File” was selected.

Rules/Guidelines for Using Code Analysis

  • Always have the Visual Studio Error window visible.  You get immediate feedback on violations following a build (as well as build errors and compiler warnings).
  • Fix violations frequently.  Fix them as they occur.  Don’t leave this as a task to be performed just before check in.
  • Always use the error help if the rule isn’t understood
  • Follow the error help code suggestions if a fix is not obvious.  Some of the IDisposable rule violations spring to mind here as particularly tricky.
  • DO NOT SUPPRESS RULES UNLESS IT IS ABSOLUTELY NECESSARY.  I cannot stress enough how important this is.  Just because a violation looks difficult to correct is certainly not a reason to suppress.  In fact, it is probably the case that the more difficult ones to address are the more critical.  I recommend that all suppressions are reviewed by a senior member of the team before being authorised.  Suppressions are rarely needed, the only suppressions I have allowed recently have been for reasons of backward compatibility.
  • If you must suppress, then choose “In Source” rather than “In Project Suppression File”.  This means that the suppression is located close to the violation so when the code is modified the violation can be validated.  If the whole method is deleted, the suppression will also be deleted.  When placed in a project suppression file, the suppressions are all too easily ignored and forgotten about.

Conclusion

Once this is embedded into your development processes, you should really start to see a reduction in defects in the code.  The development may initially be slowed as existing code is brought up to the standards required, but once this is achieved, the speed of development should be no slower.  The cost of development, however, should be less, because of the fewer defects.

At a client that I have been working with recently,  a new piece of software had been released to a customer with 2 call centres employing around 2000 users.  Memory leaks in the code meant that the application used more and more memory and resulted in it shutting down twice a day, logging off all the users and restarting.  The problem was that nothing was being disposed.  Correct implementation and use of IDisposable, as recommended by Code Analysis resolved the issues.  If the code had originally been developed with Code Analysis in place, an extremely embarrassing and costly incident would have been avoided.

See you in step 4….