Code Analysis – Minimum Rules

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.

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.

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.

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.

XML Comments and GhostDoc

The next step on our journey towards quality code involves the introduction of our first tool, GhostDoc, which is an essential tool if you want your code to be documented/commented correctly.

If your code is to be easily maintainable in the future, by the author or by someone else, it is critical that it is documented in a way that allows anyone reading or using the code to determine what a method or property is used for. We are all used to the .Net Framework code providing us with information via intellisense about a class member (i.e a method or property) and we should expect no less from our own code. Using XML comments allows us to satisfy both these requirements.

So how do we do this? Simply, when we create a method or property we add some standard XML tags immediately before the declaration, like this:

/// <summary>/// Checks that the customer name is valid. /// </summary>/// <param name="name">The name to check.</param>/// <returns>Returns true if the name is valid, false otherwise.</returns>publicbool CheckNameIsValid(string name){return(!string.IsNullOrEmpty(name)&& name.Length>1);}

Visual Studio helps us out by providing a blank template if we type 3 forward slashes on the line above the method declaration. Once comments have been created in this way, they will be associated with the method and displayed in Intellisense, making developing the software a whole lot more productive.

Providing this feature takes a little effort, but this effort is paid back almost immediately. The very next time you want to use the methods you have documented, information on what they do and the parameters required is available at your fingertips.

To make things even better, download a copy of GhostDoc and get lots of the work done for you!

This tool will actually create a significant amount of the documentation for you. Simply position your cursor on the element that you want documented, press the magic keys (CTRL + SHIFT + D by default) and GhostDoc will attempt to create your XML comments. It does this in a number of different ways, such as:

If your element is an override, it will take the XML comments from the overridden element on the base class.

If your element is part of an interface implementation, it will take the XML comment from the appropriate interface member.

For a constructor, a standard comment, including a reference to the class will be created.

For properties, GhostDoc will determine whether the property is read/write, read only or write only and generate a comment that starts with “Gets or sets…”, “Gets…” or “Sets…” as appropriate.

It looks at property types and uses language processing algorithms to do clever things like determine that an appropriate comment for a boolean property called is “IsValid” would be “Gets or sets a value indicating whether this instance is valid.”

Method names are also parsed using the same algorithms to produce method summaries. For example, a method called “SaveCustomer” will get a comment of “Saves the customer.”

If it cannot determine appropriate comments, then a blank template is generated in the same way as if three slashes had been entered.

This tool is fantastic, but you do have to put some effort into it too! The sharp eyed amongst you will have noticed that if a bit of software can use language rules to “understand” what a method or property does, then developers reading the code can do the same and so the comments are a little bit pointless.

To some extent, this is true and it is often necessary to improve the comments produced by GhostDoc in order to provide useful information beyond what can be determined simply from the method or property name. This doesn’t detract from the usefulness of the tool, however, which makes the job of documenting your code so much easier.

In step 4, we’ll see why you simply won’t be able to live without GhostDoc!

Next though, it’s step 3, where we start to see just how many bugs there are in our code!

Do you want to reduce the cost of producing your software? Do you want to reduce the number of defects, improve your customer satisfaction and make your developers (or yourself) happier? What about shorten your time to market and improve the speed at which you respond to feature requests? Of course you do! Well, I’m going to outline seven steps that you can take to enable you to achieve all these things.

My view is that software and the software development process can be massively improved by raising the quality of the written code. What I mean by that, is that I will focus, at least initially, on the code that you see, not necessarily on its functionality.

Now, I’m not claiming that this is an original idea; improving quality is one of the core tenets of most, if not all, of the Agile methodologies, but if you haven’t yet embraced Agile, are struggling with some of the techniques or aren’t seeing the results you expected then the steps I’m going to outline will reap plenty of rewards. The approach could be particularly useful if you are suffering from poor quality code provided by a third party such as contractors or offshore teams.

The Benefits

Going a little further into the benefits of taking the effort to improve your code quality, you can fully expect to see:

Reduced costs

More reliable software

Higher customer satisfaction

Quicker response to change requests

Quicker response to defects

A happier development team

These benefits arise because of:

Quite simply – fewer bugs make it into builds

Bugs are caught earlier in the development lifecycle (when they are cheaper and easier to fix)

Reduced bug counts in system test, acceptance test and in production

Reduced time in test – potentially being able to drop a test cycle or two

Reduced fix times for any bugs that do occur – but more time to do them in

Easier refactoring for improving existing code or adding new features

More productive code reviews

The Approach

The approach is based on improving the quality of .Net code. The ideas will be applicable to other languages and environments, but the specific tools that I mention will target .Net and Visual Studio.

The aim is to take small highly practical steps, one at a time, until the end result is a powerful arsenal of tools and techniques that have become an integral part of the way the development team works. Each individual step should not involve any direct costs, the tools I will introduce are free. The only investment required will be a little time, effort and discipline.

Compiler Warnings

I find it staggering how many organisations and how many developers accept and ignore compiler warnings. If you are one of these people then these incredibly useful messages are your first step in improving your code quality.
Firstly, I know that not everyone is aware of what compiler warnings are, so let me explain. When the Visual Studio compiler compiles your code, it detects potential problems in the code and produces a list for you to review. These are problems that do not prevent the code from compiling but do indicate that something should be done to rectify the situation. You’ll see something like this after compiling:

Compiler Warnings after a Successful Build - Click for full size

These two warnings indicate that something is not quite right with your code. There are a couple of variables that have been declared but never used. This means, quite simply that you have one of the following two situations:

Some unwanted declarations can be deleted (note that I said DELETED not commented out!).

Visual Studio has caught a bug for you because the variables were supposed to be used.

In either case, responding to the warning appropriately (as opposed to ignoring it) will improve your code. There are many different types of compiler warning, but they are all telling you something useful about your code. Read them and act on them!

There is an option in Visual Studio to treat some or all warnings as errors so that if any warnings occur, the build fails. Jan Van Ryswyck in this blog entry takes a hard line and declares that the default setting is “Evil” and that changing the option so that all warnings are treated as errors is “simply none negotiable”. I’m not going to suggest that you should be quite so strict with the Visual Studio setting, but I agree with the spirit of what is being said. I allow the freedom to ignore compiler warnings during periods of debugging or ‘spiking’, but compiler warnings should never be allowed to appear in checked-in code!

The important thing is to adopt a policy where compiler warnings are simply not acceptable. As I said, I don’t suggest setting Visual Studio to treat errors as warnings, but I absolutely recommend that if you are using automated builds, then the build server is set to fail a build if it encounters any compiler warnings. (If using TFS, this can be achieved easily by adding /p:TreatWarningsAsErrors=true to the MSBUILD command line).

If warnings are not treated as errors by a tool (i.e. Visual Studio or the Build Server), it is critical that the number of warnings is zero. And that means zero. Not 1 or 2 or “just a few”, but zero. There is a theory called Broken Windows Theory that suggests that if there is a derelict building its windows will stay intact for a certain period time. When one window gets broken, the others will soon follow suit and the building will deteriorate very quickly. And so it is with code, once a single compiler warning creeps in, it is then suddenly “OK to ignore warnings” and the code deteriorates. The bugs that could have been caught in our example above become lost and ignored in a sea of yellow triangles.

In conclusion then, the first step to quality code is a simple one, but an absolutely critical one. Get rid of all your compiler warnings and take the first step on the journey. Once you’ve done that, we can move on to step 2.