Experience of Code Analysis
Over the last few days I've been applying the Visual Studio 2005 Code Analysis (FxCop) to a legacy project of ours to clean up the source in accordance with the guidance embodied in the Code Analysis rules. What should have been a simple job became more complicated, as is usually the case.
The first thing I came up against was what appeared to be strange behaviours in the Code Analysis tool. Different results were returned when Code Analysis was performed on the Debug configuration than the Release configuration. Analysis rules that passed in the Release configuration failed for the Debug configuration. According to this post this can be explained by the difference in IL emitted by compiler in the two different build configurations, though I'm not 100% convinced by this explanation for reasons I'll explain in a moment.
The second issue that caused me much grief was attempting to overload the == operator in a class. This failed the rule that requires validation of parameters passed into public methods (ie checking that the parameters aren't null) before they are used. The problem is that the standard test of parameter == null causes the == operator to be called recursively resulting in a stack overflow. The solution turned out to be to implement the == operator overload as follows. The cast to object is required to ensure that the polymorphism is resolved correctly and that operator == implementation from the base object class is used to resolve whether a parameter is null. Not particulary intuitive, but easy enough once you know how. I had tried using the Object.ReferenceEquals() method to check for null, which functions correctly but still fails the Code Analysis rule.
public static bool operator ==(MyClass a, MyClass b)
{
// If both parameters are null, they are obviously equal
if (((object)a == null) && ((object)b == null))
return true;
// If only one of the parameters is null they are not equal
if (((object)a == null) || ((object)b == null))
return false;
// If both parameters are not null, apply a custom equality test
return a.Val == b.Val;
}
So why am I not convinced about the differences in IL emitted by the compiler as the reason why rules fail in Debug mode but not in Release mode? Mostly because the above operator overloading passes Code Analysis when analysed in Release mode but fails on the requirement for validating parameters when analysed in Debug mode. If in Release mode the compiler optimised the IL to remove the test for a parameter against null, the analysis test would fail because the parameter is not validated before it is used. The only way the test can pass in Release mode is if the test still exists in the generated IL and the only way it can fail in Debug mode if the test is not present. I can't figure out what would cause the test to be removed from the Debug version.
del.ico.us |
Digg It |
Technorati |
StumbleUpon |
Furl |
reddit