Friday, June 13, 2008

Code Style Review Using Microsoft Source Analysis

Today, I gave a try for Microsoft Source Analysis aka StyleCop. The tool was internally used inside Microsoft and it's now publicly released. It nicely integrates with Microsoft Visual Studio with the ability to attach the analysis process with the project build - See this post. The tool scan all your C# code and gives you hints for better coding style according to the best practices followed in writing C# code. It gives for example notes regarding the missing comments, formating, missing or extra spaces, extra blank lines and unnecessary brackets.

Here are some sample error messages resulted after running the Source Analysis on one of my projects

- The class must have a documentation header.
- The property must not be placed on a single line. The opening and closing curly brackets must each be placed on their own line.
- Property names begin with an upper-case letter: projectspath.
- All using directives must be placed inside of the namespace.
- The body of the if statement must be wrapped in opening and closing curly brackets.
- Statements or elements wrapped in curly brackets must be followed by a blank line.
- The code must not contain multiple blank lines in a row.
- All properties must be placed after all constructors.

However, there is some drawbacks regarding the tool like it targets only C# developers. More so it can't recognize the spelling mistakes in the code and comments which is one of the most common issues. Another point is that the tool is not flexible regarding its guidelines rules. It doesn't give you the option to exclude a rule in the next time of the analysis scan. For example, it consider putting a preceding underscore in the class private members as a breaking style. However, it is common for most of the C# developers. I think there is already a debate about the best style guidelines for C# coding to follow. The issue even seems to have some historical sides..

I really recommend this tool if you want your team to follow the basics of the C# coding guidelines without caring much about going in details while reviewing their code. It just help you, so that you ignore all the small crappy notes giving all your attention to the real massive mistakes in the coding logic and modules interactions.

You can find more about the tool releases and the future expectations in the Source Analysis blog.