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.
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
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.
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.
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.
How to shut off a rule for just one method: Suppress Message Attribute.
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.
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.
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.