Code Analysis – Further Rules

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:

Selecting the Multiple Rule Sets Option

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

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:

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.

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 2010

Visual Studio 2013

Microsoft Basic Correctness Rules

Basic Correctness Rules rule set for managed code

Microsoft Basic Design Guideline Rules

Basic Design Guideline Rules rule set for managed code

Microsoft Extended Correctness Rules

Extended Correctness Rules rule set for managed code

Microsoft Extended Design Guideline Rules

Extended Design Guidelines Rules rule set for managed code

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.

StyleCop

How often have we heard things like “Steve wrote that – I’m not touching it!” or “That came from the offshore team – it’s a mess”? Often, this is down to a question of personal style. The code in question may be perfectly readable and maintainable to the developer who wrote it, but not to anybody else.

If we want robust and maintainable (i.e. quality) code then a standard style, consistent across the whole team or organisation, is what is required. If the code is always written in the same style, then developers can focus on functionalty and correctness rather than being distracted by inconsistencies in coding styles.

As with the other steps, this isn’t a new idea, It has long been recognised that some sort of corporate “Coding Standard” is useful. This would perhaps specify common standards for all code – things like layout, formatting, casing, naming conventions etc. Traditionally, if an organisation has a view on these things, lots of effort would be spent in devising the standard and creating a “coding standards” document hidden away on a server somewhere. New developers typically have this document on a list of “documents to read” as part of their induction. In my experience, that’s usually as far as it goes. The practicalities mean that enforcing the corporate standard is simply too difficult and so the code rarely, if ever, actually conforms to the standard. Each developer uses their own view of “standard practice” and these views often differ widely.

In this fourth step, we are going to address these issues. The approach is to discard the Coding Standards document and instead introduce our next tool – StyleCop. This tool was originally developed to enforce standards on internally created code in Microsoft but was then released for public use. In 2010, it became open source and is now available on the StyleCop CodePlex page. In a similar way to Code Analysis/FxCop introduced in step 3, it analyses code against a set of predetermined rules. The difference between the two tools is that Code Analysis looks at the compiled assemblies, whereas StyleCop looks at the contents of your source files. There are some overlapping areas, but StyleCop will focus on what your code looks like, rather than how it behaves.

Like Code Analysis, rule violations are reported in the Visual Studio Error window, as shown below:

Also like Code Analysis, detailed explanations can be found by right-clicking and selecting “Show Error Help”. Unlike Code Analysis, individual rule violations cannot be suppressed. This is not important with StyleCop as the rules are more objective and not prone to exceptions like Code Analysis rules.

It is possible to switch off a rule entirely, but I would strongly recommend not doing this. My approach is to leave the rules in their default state. This leads to a much simpler situation for ongoing configuration management as there is no configuration required by project, solution, developer or machine. Additionally, there are rules that complement each other and work together “as a set”. For example, the common practice of prefixing class level fields with an underscore is outlawed under StyleCop, but this practice is complemented by a rule that insists that these fields are preceded by “this”.

Some of the rules may seem a little strange at first. The aforementioned rule about not prefixing with underscores being a good example if you have been used to this previously, using statements having to be inside the namespace being another. However, it takes a surprisingly short period of time before the standard StyleCop format becomes “the norm” and non-compliant code is jarringly wrong.

The real beauty of using StyleCop is that it quickly becomes possible to see past what the code looks like (because it’s always the same) and see what it is doing. Errors in logic or function jump out of the page in a way that is simply not possible when everyone codes to their own style.

Rules/Guidelines for Using StyleCop

These are similar to the guidelines for Code Analysis.

Stick with the default rule settings.

Incorporate StyleCop into your process. Configure it to run each time the solution is built. If you have an automated build, incorporate it there.

Always have the Visual Studio Error window visible. You get immediate feedback on violations following a build (as well as build errors, compiler warnings and Code Analysis violations).

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. There is often interesting commentary on the rationale behind the rule. In the early days, it’s worth looking at the help even when you think you understand the rule.

Use GhostDoc. StyleCop is hard work without it, GhostDoc becomes absolutely essential.

Persevere. It can be daunting to see a single class with 600 violations, but this means there is massive scope for improvement in such a class and so the benefits and the feeling of accomplishment once it’s done will be worth it.

Once the use of StyleCop is embedded, you will be well placed to move on to step 5...

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!