Search code examples
visual-studiovisual-studio-2010code-analysisfxcopca1062

Should I suppress CA1062: Validate arguments of public methods?


I've recently upgraded my project to Visual Studio 2010 from Visual Studio 2008.

In Visual Studio 2008, this Code Analysis rule doesn't exist.

Now I'm not sure if I should use this rule or not.

I'm building an open source library so it seems important to keep people safe from doing mistakes. However, if all I'm going to do is throw ArgumentNullException when the parameter is null, it seems like writing useless code since ArgumentNullException will be thrown even if I won't write that code.

EDIT: Also, there is a performance issue that needs to be addressed. Checking for null in every public method can cause performance issues.

Should I remove that rule or fix the violations?


Solution

  • That depends. The convention when using ArgumentNullException is to include the name of the null argument in the description. So the caller will know exactly what went wrong.

    The source of a NullReferenceException (which is what will happen if you don't validate) may be easy to spot, but if the method is complex it may be more difficult. You may end up at a line of code where multiple references could be null.

    Personally I prefer to have public methods throw ArgumentNullException if they cannot handle null input for the given argument, because it allows for a consistent behavior no matter how the method is implemented.

    In reply to edit: In my opinion it is more important to provide a consistent set of interfaces with few surprises than optimizing every line of code. My guess is that in most cases the performance overhead of the null check will not be significant. If it does turn out to be a problem (as in profiling says so) I would consider changing it. Otherwise I wouldn't consider it a problem at this point.