Tag Archives: Tools

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

SQL Search from Red Gate

I’ve recently been introduced to a fantastic free tool from Red Gate, who provide several software packages for use with SQL Server. I’ve used their SQL Compare tool for a few years now and it’s been great, but only gets used on an occasional basis.

SQL Search, however, has become my best friend! It’s an add-in that integrates into SQL Server Management Studio and allows you to search for specific text across all your database objects. Once it’s indexed the database, it’s incredibly quick, in fact instantaneous (I’m working at the moment on a database with around 1000 tables and 3000 stored procedures).

One of the first things I do when I start working on a new database is script out all the stored procedures and triggers and save the result so that I can find where particular tables or columns are used. With SQL Search, I no longer need to do this and don’t have the disadvantage of the scripted objects going out of date.

SQL Search has almost become my starting point for my use of SQL Server. If I want to view or modify a particular stored procedure, it’s easier to type part of the name into SQL Search than it is to search for it in object explorer. If I’m just wanting to view it, it’s instantly available in the preview pane as soon as I click it in the search results. If I want to go further, the very useful “Select Object in Explorer” link is available.

There are a couple of improvements I’d like to see. Firstly, at the moment, if two words are entered it returns results containing either of the words. This isn’t the default behaviour I would have chosen, it makes more sense to me that the results should contain both the words. Changing this or allowing a boolean search would be a definite advantage.

Secondly, it would be nice to see the code in the preview pane coloured coded in the same way as in Management Studio rather than being presented in plain text.

Overall though, a fantastic product and best of all, it’s free (for now at least!).