when validating methods' input, I used to check if the argument is null, and if so I throw an ArgumentNullException. I do this for each and every argument in the list so I end up with code like this:
public User CreateUser(string userName, string password,
string Email, string emailAlerts,
string channelDescription)
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("Username can't be null");
if (string.IsNullOrEmpty(Email))
throw new ArgumentNullException("Email can't be null");
//etc, etc, etc
}
Is this OK? Why should I do this? Would it be ok if I simply group all the checks and return a null value instead of throwing the exception? What is the best practice to address this situation?
PS: I want to change this, because with long methods, it gets very tedious to do so.
Ideas?
And for the C# 3.0 developers amongst us a great way to encapsulate this null checking is inside an extension method.
And if you wanted you could always overload that to take an argument name.
An approach which I use and I may have picked up from the NHibernate source is to create a static class
Guard
, used as follows:This cuts down a lot of the chaff at the beginning of methods and it performs well.
I would stick with your original approach, except for just passing in the parameter name. The reason is that once you start writing those helper procedures it becomes an issue when everyone starts using different conventions for how they write the helper procedures. When someone looks over your code, they now have to check to make sure you've written the helper procedure correctly when debugging your code.
Keep checking each argument separately, though youor fingers grow weary from typing Grasshopper :) Your followers will bless you when they get the unexpected ArgumentException and are saved from a debugging run just to determine which argument failed.
Make an ArgChecker class with something like this
where ThrowOnStringNullOrEmpty is
You could also try to process a list of arguments using a params arg, like:
and call like this
A small improvement to Lou's answer would be to use a hashtable instead, it means it checks objects aswell as just strings. Also just nicer to populate and handle in the method:
As you would use like:
My first advice to you is get ReSharper. It will tell you when there is a problem of possible null values, and when there is no need to check for them, and with the click of a mouse will add checking. Having said that...
You don't have to check for int or bool, which cannot be null.
Strings can be checked with string.IsNullOrEmpty()...
If you still decide that you want to check each and every parameter, you can either use the Command design pattern, and reflection, but your code will be unnecessarily clunky, or use the following and call it for each method: private myType myMethod(string param1, int param2, byte[] param3) { CheckParameters("myMethod", {param1, param2, param3}); // rest of code...
And in your utility class put this: