InfoQ

InfoQ

News

My Bookmarks

Login or Register to enable bookmarks for unlimited time.

The content has been bookmarked!

There was an error bookmarking this content! Please retry.

StyleCop – Microsoft's Style Enforcement Tool for C#

Posted by Jonathan Allen on May 28, 2008

Sections
Development,
Architecture & Design
Topics
.NET ,
Syntax ,
Programming
Tags
C# ,
StyleCop ,
Coding Standards

Style enforcement has long been a hotly debated topic. Not only are their arguments over what style a team should standardize on, but also on whether or not there should be a standard style at all. In a move that is sure to add fuel to the flames, Microsoft has released StyleCop, the style enforcement tool they use internally.

StyleCop, also known as Microsoft Source Analysis for C#, is the source code equivalent of FxCop. Like FxCop it was originally used within Microsoft and has grown to the point where Microsoft sees it being useful to others. But unlike FxCop, it is not highly configurable.

The ultimate goal of Source Analysis 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, Source Analysis does not allow its rules to be very configurable. Source Analysis 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! However, the majority of teams using this tool within Microsoft have found that after a short adjustment period, they came to appreciate the rules enforced by Source Analysis, and even began to find it difficult to read code not written in this style.

Jason Allor claims the 200 some rules enforced by the tool are compatible with the default settings found in Visual Studio. Unfortunately, he neglected to mention that Visual Studio comes with 6 very different default-setting collections, many of which directly contradict this tool.

The areas it tool covers include,

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

Running these rules against an empty console application returns 9 errors, 16 if you have "Keep Tabs" turned on. Some of the rules are rather awkward such as requiring "using" directives to be inside of the namespace instead of at the top of the file.

Already there are complaints about the tool's lack of corrective support. Dustin Norman writes,

As someone who just ran this tool on a rather small assembly, I'm kind of overwhelmed at the idea of fixing 561 violations manually when the tool could fix them for me automatically without affecting the semantics of the code.

The age-old debate over tabs vs spaces has come up again, as well as the inability to disable specific rules. Nick Berardi writes,

Are you kidding me. Tabs are not allowed. Use spaces instead. This is a horrible idea, because it throws blocking layout off, if one variable uses 3 spaces and the other uses 4. This there anyway to disable some of the more pointless rules like this tab one.

It would be nice if you were able to disable some of these rules. I know you said they are for the best. But I totally disagree with this tab over spaces. There is no logical reason for it. Except some holy war that has been battled out between developers since Vi first came to market. I would love to run this over my source code, but it blows up because it alerts me about every line that has a tab in it.

Meanwhile Daniel Stolt asks about VB,

This is a very welcome addition to the set of tools available for .NET developers - but why only for C#? Enforcement of code formatting rules is just as sorely needed for VB developers!

Admittedly, the VB code editor has some rudimentary support for automatic formatting when it comes to indentation and spacing around keywords and symbols, but nothing that even comes close to what StyleCop supports.

By the way, I totally agree with "nberardi" [Nick Berardi] on the tabs vs. spaces issue: what is the problem with tabs? Is it somehow an advantage to have to press the arrow key 4-5 times more to get to a given point? Is it somehow an advantage to have to store 4-5 times as many whitespace characters in a source file?

There does seem to be some interest in at least supporting automatic correction, but no timelines were given.

People hate being told they're not perfect by Francois Ward Posted
Re: People hate being told they're not perfect by Jeff Santini Posted
And, on the automated topic ... by bob munger Posted
  1. Back to top

    People hate being told they're not perfect

    by Francois Ward

    This is really all this is... C# needs a standard. Too many C++ devs coming with their m_ prefixes and screaming caps constants (which btw isn't a new standard: its part of the design guidelines that have been published forever ago). Too many VB6 devs who missed the memo about hungarian notation. Too many Java devs who see C# as a Java clone and thus keep the same standards.



    The result is that if you go to a random company XYZ and look at their code, then go to company ABC and look at their code, it will be totally different, and you have to relearn how to "read" C# everytime. At least in Java-land, various code bases at least are SOMEWHAT similar... This tool is there to fix the issue.



    For the tabs vs space, there had to be one standard, and they picked one. No matter which they picked, people would have complained, and allowing both defeats the purpose of the tool (the tool is NOT to help your organisation manage your standards. Its the now semi-official C# recommendation, and there's an attached tool to enforce it, unlike FxCop's purpose).

  2. Back to top

    Re: People hate being told they're not perfect

    by Jeff Santini

    "For the tabs vs space, there had to be one standard"
    Why?

    How does allowing both defeat the purpose of the tool?

    The purpose according to the blurb at the top is to:
    "allow you to produce elegant, consistent code that your team members and others who view your code will find highly readable"

    Those are two seperate goals, that are each subjective. The idea that there can be one best way to achieve two seperate goals that cannot be objectively evaluated seems a bit niave to me.

    I will be happy to use whatever standard allows my team produce value for our users, and I am sure there is more than one. If the day comes that we are so outside the norm that new joiners can't understand our code we can think about changing. I would be afraid that someone who gets hung up about tabs versus spaces could be spending their time more productively worrying about the quality of the binaries they are shipping.

  3. Back to top

    And, on the automated topic ...

    by bob munger

    For me, the most important part of Johnathan's note was the reference of automation of StyleCop. In my opinion, this should be a high priority. I have happily embraced consensus standards for white space/use of brackets/etc. But it is impractical to apply recommended changes to a large existing code base. Being able to apply changes before check-in or at build time or to all files in a large code base would make this tool far more valuable for development.

Educational Content

New-age Transactional Systems - Not Your Grandpa's OLTP

John Hugg discusses high volume transaction processing applications with high and low frequency profiles, and how VoltDB can be used for that purpose.

Cool Code

Kevlin Henney examines code samples to see what can be learned from them starting from the premise that one won’t write great code unless he knows how to read it.

Collaboration: At the Extremities of Extreme

Jason Ayers share the observations he made watching a team of developers collaborating in real time on the same code base, pushing XP, pair programming and continuous integration to their extremes.

Yesod Web Framework

Michael Snoyman presents Yesod, a web framework written in Haskell and containing a web server, templating, ORM, libraries (templating, gravatar, etc.).

Transactions without Transactions

Richard Kreuter and Kyle Banker on how to avoid classical RDBMS transactional systems by using compensation mechanisms, transactional messaging or transactional procedures.

Attila Szegedi on JVM and GC Performance Tuning at Twitter

Attila Szegedi talks about performance tuning Java and Scala programs at Twitter: how to approach GC problems, the importance of asynchronous I/O, when to use MySQL/Cassandra/Redis, and much more.

10 tips on how to prevent business value risk

One category of risk that project teams need to ensure they address is business value failure – delivering a product that fails to provide value for the business investor.

Interview: Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives

InfoQ spoke to the authors of Software Systems Architecture on a couple of new topics, the System Context viewpoint and Agile, which have been added to the second edition.