No Code Review? No Unit Testing? Code Analysis To The Rescue!

Introduction

This article is about Code Analysis in Visual Studio 2005 Team Edition, and how it can help you improve the quality of your code. This article by no means is trying to tell you that you no longer need proper unit testing and code reviewing practices, but highlights a new tool that helps improve code in general.

Background

About a year ago, I was ending my relationship with a Biotech company where code reviews and unit testing were not only welcome, but expected before turning your code over to the SQA department prior to being methodically trounced before being sent to production. I was moving to a new company in the home audio arena, working in the IT department, where requirements consisted of the phrase, “it just needs to get done”. My goal in this company was to train the existing staff and any new staff on the use of Visual Studio 2005 and the .NET Framework 2.0, while striving to maintain a level of quality in the code that I turned out.

First, I suggested automated unit testing to the team. Something like NUnit, but new in VS 2005 team editions is a built in unit testing framework very similar to NUnit that I thought we should use. I was hoping to keep everything in one suite to make the transition from PHP, and VB6 as “painless as possible”. When I suggested unit testing, I was greeted by the blank stares you would expect when driving your car into a heard of deer. I figured that I would not get a lot of support here.

Next, I suggested code reviews. Similar response as the unit testing, but more like throwing a cat into a dog house while the dog is inside.

You see, the group I have found myself with, on a regular basis, wrote all of their code on production web servers, while the users/customers were actively using the application. I won't go into a great deal of detail, but suffice to say, I was able to stop that practice for all new .NET code, and most of the existing applications as well. I even got them to use source control, but that’s a different story.

So, what am I left with? Well, in Visual Studio 2003, and .NET 1.x, there was this slick tool called FxCop, which would basically analyze your code and help you find problems with it. The problem here is the same as the others; the act of installing FxCop was too much to expect, let alone running it on a regular basis, and there was no guarantee that they would even fix the problems found. Visual Studio 2005 and Code Analysis to my rescue!

Built into Visual Studio 2005 (this is only available in the Team Editions) is code analysis. Basically it's FxCop, but it's part of Visual Studio! I can turn on code analysis for a project, and it will run each and every time I compile my project! I can set warnings, and, you're going to love this; ERRORS, which will act just like compiler errors. Your project won't compile until you fix the problem.

So what does this all mean? Well one example would be; “Types that own disposable fields should be disposable”, which essentially means that when you create a class, and you create an object in that class that must be disposed of, you will be forced to do so. The result is that now you have cleaned up after yourself, and made the work of the Garbage collector easier. Resulting in less time that your object sits in memory, and less work for the GC to get rid of it, so less CPU used by your end user. Perhaps even resulting in less “The application is slow” bugs reported by users.

Another good example might be “Remove unused locals”. This will give a warning or error, depending on your preference, when you have unused local variables in your code. Not a huge deal, but it does keep your code neat and tidy to remove them.

How to Enable Code Analysis

Figure 2

So, how do I activate code analysis for my projects? It’s a bit different between Class Libraries/WinForms projects and Web projects. I'll start with Libraries/WinForms Projects since that covers 2 out of 3 project types.

Right Click on a given project in your solution explorer, and select “Properties”. You will be shown a screen similar to that of figure 1 at the top of this article. Now click on the tab that says “Code Analysis”, and click the check box that says “Enable Code Analysis”. Congratulations, you have just enabled code analysis for your project.

Figure 3

What you have now is the task, (I'll admit it can be tedious), of choosing the rules you want to enforce, and setting them to either a warning or an error. By default they are all turned on, and set to warning. To change the rule from a warning, to an error, simply click on the Warning, or Error icon, and the rule will be switched. I suggest setting a few each day until you're happy with what you have. Besides, you may find that setting too many at once will become overwhelming.

Setting Code Analysis for a web project is a bit different, but just as easy. The main difference is that you will need to select your web project in the solution explorer, but rather than right clicking, you will go to the tool bar in VS2005, and select “Website” and then “Code Analysis Configuration”. All of the other steps are the same.

If you're not sure what a particular rule means, you can just select it, and press F1, which will bring up VS2005’s help, and will describe what the rule means, an example of breaking and fixing the rule. Also, if you enabled a rule, and now your project won't compile, you can right click on the error, and select “Show Error Help”. This will bring up the same screen and will describe how to fix the problem.

Recommendations

I have found that my biggest offending code base is in the security rules. I have elected to turn them all on, and set them all to error. This took me several days to go through all of my code and fix all of the offending errors, but I now feel that my code is more secure than it otherwise would have been.

I suggest turning on “Disposable Fields Should Be Disposed” in the usage rules.

I also suggest “Dispose Objects Before Losing Scope” in the Reliability rules.

There are several others, but I will leave them to you. I find that from time to time, I go through the list and add a few new ones to help tighten up my code.

Miscellaneous Tidbits

How to copy your rules from one project to another (Does not apply to VS2005 Web Projects without SP1): This is a bit of a hack, so be prepared. Basically a VS2005 project file is an XML MSBuild file, so you can open the file in Notepad and edit it. (You know where I am going I bet). So, you can open up the project you just configured in Notepad, and look for the element "CodeAnalysisRules". Copy everything between that opening element and its closing "/CodeAnalysisRules" and add it to your new project, making sure RunCodeAnalysis is set to true in your new project as well. Next time you open that new project, and look at your code analysis rules, they should match your first project.

You may notice that your compiler now runs a “bit slower”. Well code analysis is a very intensive process and it may slow down your compile times, but it may very well pay off in the end. Keeping you from logging those 20 hour days trying to figure out why your application isn't serializing objects correctly.

Conclusion

Enabling Code Analysis is by no means a replacement for proper code reviews, and unit testing. It’s just another tool to help you turn out quality code, and if you're in an environment where code reviews and unit testing are performed, this may very well help keep that code reviewer off your back, and make you look like a master coder. If you can't find the time or man power for unit testing and code reviews, then this may just keep the number of subtle bugs in your code to a manageable level.

I have to say, since turning on code analysis, I have seen the number of bugs in my teams projects go down, and I have seen the quality of the code turned out improve dramatically from the most junior to the most senior developer in the team. I have also seen applications with a tendency to leak memory, not only stop doing so, but run often with a smaller footprint.

Try it out and be your own judge. I like this because it's built into the IDE and I can enforce it on the team without them really needing to know that the extra rules are even there.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

Share

About the Author

I started in the Oil field industry as a system admin and a web developer using classic ASP and Oracle for 3 years. Biotech for 2 1/2 years using ASP.NET/C#, and now I am working for a home audio company in the IT Department developing .NET 2.0 applications.

It also comes from with advanced code visualization (Dependencies Matrix, Metric treemap, Box and Arrows graph...), more than 60 metrics, facilities to generate reports and to be integrated with mainstream build technologies and development tools.

NDepend also allows to compare precisely different versions of your codebase.

I appreciate your input suggesting a 3rd option to Code analysis, and FX cop. However, the point of the article was about code analysis, and its integration into Visual Studio. I also don't believe that this part of code project is the appropriate place for product advertisement. There is a place for that in code project, but community submissions are not that place.

how to review codebind files(UI-web app) using fxcop, I mean how to integrate fxcop into visual studio so that when we build it will automatically reviews code. I am not getting code analysis section like what you have shown in the article. Pls help me regarding this.

The code analysis feature is only available in Visual Studio 2005 Team editions. So if your running VS Pro, or Standard, or even the express editions, then the Code analsys feature is not available.

As far as intergrating FXCop into Visual Studio so it runs automaticly, I have never personaly done this. However, I do know that FX Cop can accept command line input, and you could set up a post build event to run FX Cop after you compile your assembly. You can do this with any version of Visual Studio 2002, 2003, or 2005.

Hi,
I am new to classic ASP programming. I am developing a web application in classic ASP using Visual studio 2003. Could you please give me a head start on how to perform UNIT Testing on this application in this environment. Are there any inbuilt tools in VS 2003 for UNIT Testing?. Thank you...

In the Biotech world, I was a "SR Software Engineer", so I had the ability to affect some change, but not very much. I was stuck in meetings and the amount of paperwork being FDA regulated was beyond boring. I simply got tired, and wanted a change. This new position gives me an opportunity to effect a lot of change, and there are constant challenges. The biggest thing is that I can see on a daily basis how my contributions affect the company, and the people in it.

There is a small reference to "team edition" with respect to unit testing. I would have expected more emphasis on the fact that the Code analysis capability only comes with the VSTS version of VS 2005.