Click here to Skip to main content
15,867,453 members
Articles / Operating Systems / Windows

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

Rate me:
Please Sign up or sign in to vote.
4.62/5 (12 votes)
17 Oct 20068 min read 69.6K   49   19
The benefits of Code Analysis in VS 2005
Visual Studio 2005 Project Code Analysis Properties
Figure 1

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

Visual Studio 2005 Solution Explorer
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.

Visual Studio 2005 Solution Explorer
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 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.

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.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
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.

Comments and Discussions

 
GeneralCustom Code Analysis Pin
Chris_McGrath15-May-07 15:57
Chris_McGrath15-May-07 15:57 
GeneralRe: Custom Code Analysis Pin
Russ Harding16-May-07 1:56
Russ Harding16-May-07 1:56 
GeneralNDepend Pin
Patrick Smacchia MVP.NET6-May-07 12:52
Patrick Smacchia MVP.NET6-May-07 12:52 
Folks interested in FxCop should have a glance at the tool NDepend:
http://www.NDepend.com

NDepend analyses source code and .NET assemblies. It allows controlling the complexity, the internal dependencies and the quality of .NET code.

NDepend provides a language (CQL Code Query Language) dedicated to query and constraint a codebase.

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.

Patrick Smacchia
MVP.NET
Author of Practical .NET2 and C#2
Author of NDepend

GeneralRe: NDepend Pin
Russ Harding7-May-07 12:33
Russ Harding7-May-07 12:33 
GeneralRe: NDepend Pin
psmacchia7-May-07 22:47
psmacchia7-May-07 22:47 
Questionreviewing code behind Pin
Phani Sirigala16-Nov-06 3:59
Phani Sirigala16-Nov-06 3:59 
AnswerRe: reviewing code behind Pin
Russ Harding16-Nov-06 12:58
Russ Harding16-Nov-06 12:58 
GeneralRe: reviewing code behind Pin
_SET7-Feb-11 5:13
_SET7-Feb-11 5:13 
GeneralV Gud Pin
qumer10117-Oct-06 22:41
qumer10117-Oct-06 22:41 
GeneralRe: V Gud Pin
Russ Harding18-Oct-06 1:05
Russ Harding18-Oct-06 1:05 
QuestionWhy ? Pin
megaadam17-Oct-06 21:24
professionalmegaadam17-Oct-06 21:24 
AnswerRe: Why ? Pin
Russ Harding18-Oct-06 1:04
Russ Harding18-Oct-06 1:04 
GeneralRequires VS Team System version Pin
jsytniak17-Oct-06 18:39
jsytniak17-Oct-06 18:39 
GeneralRe: Requires VS Team System version Pin
Nicholas Brookins17-Oct-06 19:19
Nicholas Brookins17-Oct-06 19:19 
GeneralRe: Requires VS Team System version Pin
Dec0mpile17-Oct-06 20:44
Dec0mpile17-Oct-06 20:44 
GeneralRe: Requires VS Team System version Pin
mtone23-Oct-06 13:30
mtone23-Oct-06 13:30 
AnswerRe: Requires VS Team System version Pin
Russ Harding18-Oct-06 1:00
Russ Harding18-Oct-06 1:00 
GeneralRe: Requires VS Team System version Pin
Marcus_218-Oct-06 1:34
Marcus_218-Oct-06 1:34 
GeneralRe: Requires VS Team System version Pin
Russ Harding18-Oct-06 0:55
Russ Harding18-Oct-06 0:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.