Category Archives: .Net

Seven Steps to Quality Code – Step 4

StyleCop

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

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 functionality 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.

A sample of the things that StyleCop will report are as follows:

  • Incorrect casing of variables, method names, property names etc.
  • Incorrect naming conventions (e.g. use of underscores)
  • Missing XML comments
  • Non-standard XML comments (for example, read/write properties must start with “Gets or sets…”)
  • Incorrect spacing around operators, brackets, commas etc.
  • Missing curly brackets
  • Missing and superfluous blank lines

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

StyleCop Warnings

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...

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….

Seven Steps to Quality Code – Step 2

XML Comments and GhostDoc

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

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>
public bool 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:

  1. If your element is an override, it will take the XML comments from the overridden element on the base class.
  2. If your element is part of an interface implementation, it will take the XML comment from the appropriate interface member.
  3. For a constructor, a standard comment, including a reference to the class will be created.
  4. 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.
  5. 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.”
  6. 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.”
  7. 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!

Seven Steps To Quality Code – Introduction

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.

The Steps

  1. Compiler Warnings
  2. XML Comments and GhostDoc
  3. Code Analysis – Minimum Rules
  4. StyleCop
  5. Code Analysis – Further Rules
  6. Peer Reviews
  7. Unit Tests

Let’s get started with step 1 – Compiler Warnings