Jan Schreuder on .Net

.Net code samples, experiences, observations

View my professional profile on LinkedIn

Recent Posts

Tags

News

  • Inappropriate comments will be deleted at my discretion.

    The information and code samples in this weblog is provided "AS IS" without warranty of any kind, either expressed or implied, including but not limited to the merchantability and/or fitness for a particular purpose.

Community

Email Notifications

Tool suppliers

Tools

General

Microsoft

Favorite blogs

Archives

Have your C# coding style analysed by Microsoft!

Or to be more specific, by Microsoft StyleCop. Now this may not be new to you, and that's very likely since StyleCop was announced in May of this year, but it was new to me.

The tool checks your code for coding style and more specific, the Microsoft coding style. It was developed outside the VSTS team and has absolutely no connections to FxCop. FxCop focusses on .Net Framework standards and correct use, StyleCop focuss on the way your code looks. Among others, it checks your code for the following items:

  • Layout of elements, statements, expressions, and query clauses
  • Placement of curly brackets, parenthesis, square brackets, etc
  • Spacing around keywords and operator symbols
  • Line spacing
  • Placement of method parameters within method declarations or method calls
  • Standard ordering of elements within a class
  • Formatting of documentation within element headers and file headers
  • Naming of elements, fields and variables
  • Use of the built-in types
  • Use of access modifiers
  • Allowed contents of files
  • Debugging text

The idea behind StyleCop, as can be read on their teamblog:

The ultimate goal of StyleCop is to allow you to produce elegant, consistent code that your team members and others who view your code will find highly readable. In order to accomplish this, StyleCop does not allow its rules to be very configurable. StyleCop takes a one-size-fits-all approach to code style, layout, and readability rules. It is highly likely that you will not agree with all of the rules and may even find some of the rules annoying at first!

 

I downloaded the tool (click here) and installed it to test drive it on my CrystalHelper class, and boy are they right. Some of those rules are annoying. I previously checked that class with FxCop and got little to comments there. From people that used the code, I always received comments that is was readable, easy to comprehend, etc. Then again, those differences make sense. FxCop looks at usage of the .Net Framework and does so by analyzing the compiled binaries. StyleCop uses the actual code. But let me give you some examples of what StyleCop has to say about my code.

Running StyleCop

The first thing I noticed when I ran StyleCop (or Source Analysis as it's called in the menu) is the enormous amount of comments. My first reaction was to remove the tool and forget about it. Actually, I had the same reaction when I first ran FxCop. I was curious enough to continue though, so let's look at what the tool had to say about the following code segment.

  489         /// <summary>
  490         /// Gets or sets the data source.
  491         /// </summary>
  492         /// <value>The data source.</value> 
  493         public DataSet DataSource 
  494         { 
  495             get 
  496             { 
  497                 return _reportDataSource; 
  498             } 
  499             set 
  500             { 
  501                 if (_reportDataSource != null) _reportDataSource.Dispose(); 
  502  
  503                 _reportDataSource = value
  504             }
  505         }

Here we have 16 lines of code which most C# developers will accept as properly styled. StyleCop however gave me remarks about almost every line of code code:

  • Tabs are not allowed. Uses spaces instead. On almost every line.
  • The call to _reportData must begin with the 'this.' prefix to indicate that the item is a member of the class. On lines 497, 501, 502 and 504.
  • Statements or elements wrapped in curly brackets must be followed by a blank line. On line 498.
  • The body of the if statement must be wrapped in opening and closing curly brackets. On line 501.

In addition to this, it also mentioned that the fieldname should not start with an underscore. This was a remark abou the _dataSource class variable I use in this property code. For this section of code, I received a total of 23 comments!

Changing the code to satisfy the tool

As I said, most C# developers will not really have a problem with the coding style used in the above segment. But apparently, this is totally unacceptable for Microsoft developers. My next step was to change the above code so that the tool would not complain about this code. And this is what it looks like after those changes:

  489         /// <summary> 
  490         /// Gets or sets the data source. 
  491         /// </summary> 
  492         /// <value>The data source.</value> 
  493         public DataSet DataSource 
  494         { 
  495             get 
  496             { 
  497                 return this.ReportDataSource; 
  498             } 
  499  
  500             set 
  501             { 
  502                 if (this.ReportDataSource != null
  503                 { 
  504                     this.ReportDataSource.Dispose(); 
  505                 } 
  506  
  507                 this.ReportDataSource = value
  508             } 
  509         }

All tabs are now replaced with spaces. The body if the if statement is now enclosed in brackets. There's an empty line after the closing brackets for the get body and the if body. All class members are now preceded by 'this.'. And yes, I removed the underscore from the class member. Not that much different, but some of the changes make sense, I guess.

Other comments found by the tool

The tool does find other things as well. Here's a short list of some other comments the tool made about my CrystalHelper class:

  • Invalid spacing around the comma. All comma's should be followed by a single space
  • Invalid spacing around the opening parenthesis. There should not be a single space after an opening parenthesis
  • Invalid spacing around the closing parenthesis. There should not be a single space before a closing parenthesis
  • The spacing around the symbol '=' is invalid. You need to add a single space before and after the '='symbol
  • All using directives must be placed inside of the namespace
  • All methods must be placed after all constructors
  • All methods must be placed after all properties
  • All private methods must be placed after all protected methods
  • All private methods must be placed after all public methods
  • All protected constructors must be placed after all public constructors
  • The method must have a documentation header
  • The summary section in the documentation header must not be empty

Should you use it?

A difficult question. My first reaction, as I said before, was to remove the tool and forget about it. But that was the same reaction I had when I first started using FxCop. And yet, that is now a tool I use on a daily basis.

I also have a problem with non-enforceable coding standards. Put 10 developers in a room to talk about coding standards and you end up with either 10 slightly different versions, or one that none of them will adhere to. My experience over the last 20 years is that, if you can't enforce coding standards, you can forget about introducing them and hope that it will all go well.

And that's exactly where this tool comes in. You can now enforce a number of rules to make code more readable and understandable. You might want to disagree to some of them (I don't agree to using spaces instead of tabs) but you can run the tool and check if your coding style matches that of the tool. And when all developers in your team use the tool and change their code accordingly, then all your code looks quite similar. Making it easier for your teammembers to work on code by other developers. And that's the main objective for any development team to create a coding standard.

The tool can also be included in MS-Build scripts, so you can easily make sure the build is broken when a developer ignores the coding standard. So yes, use it!

Some tips when using StyleCop

Once you have installed the tool and are ready to check your code using the tool, you might want to consider doing the following first:

  1. Go to the C# section in Tools -> Options -> TextEditor and change the properties for the tabs so that it inserts spaces and click the OK button
  2. Open the class file and select all code using CTRL-A
  3. Now hold the CTRL key and press K, followed by F. This automatically re-aligns the entire class and replaces any tabs in your code with spaces. Do this for all class files in your project.

When you do this, the following will happen in your code.

  • Tabs are converted into spaces
  • Spacing before and after open and closing parenthesis is adjusted
  • Spacing around symbols is adjusted

StyleCop will not give yo any comments about those items. Which leaves the more interesting items to fix.

What's next for StyleCop?

Like all Microsoft tools, this is a work in progress. New features and options will be added and bugs will be fixed. But for the near future, the following has already been announced:

  • The tool is still called Source Analysis when you look for it in the Tools menu. It will be renamed to StyleCop
  • A small SDK will be made available to allow you to extend the tool with your own rules
  • Documentation about the currently available rules (which in fact opens up the Microsoft C# coding standards to the community)
  • Automatically change your code to enforce some of the rules

So keep an eye on the StyleCop blog for future releases of this tool. I will be discussing the tool with my team as soon as possible and start using it. Finally a way to have our code look similar!

Comments

John Doe said:

I find StyleCop quiet interesting, but I disagree with some of the rules and it's sad if you cannot configure them, so you cannot enforce your own corporate coding style.

What bugs me even more is that I have to "correct" all those issues manually so that tool does not save me any work, instead it causes even more.

That is why I prefer a tool that *automatically* applies our *custom* styles to the source. This is why I love ReSharper where you can define your own settings and it can even apply it to your whole solution at your fingertips.

So, my conclusion on StyleCop is: Nice idea, but barely handy.

# July 25, 2008 2:50 PM

Jan Schreuder said:

I don't agree with some of rules either, but I tend to have that with almost all coding standards. All of them have one or more rules I don't really like or even completely oppose. However, Microsoft are promissing some degree of fine-tuning and will focus on automatic correction if that is possible. So for me this will do, eventhough ReSharper is better at customizing.

# July 25, 2008 2:59 PM

Jan Schreuder on .Net said:

If there's one thing that developers usually just cannot (or will not) agree to, then it's Coding

# July 25, 2008 10:11 PM

Anon said:

I opened up some code today to find that a coworker who needed to change something decided to have ReSharper remove most of the parenthesis when if/else blocks had a single statement...

# May 15, 2009 7:20 PM

Jan Schreuder said:

having parenthesis on if/else blocks with a single statement is a matter of opinion. I myself would smack the person that removed them, I always add parenthesis. It can prevent errors.

# May 15, 2009 7:30 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Please add 1 and 8 and type the answer here: