DevPinoy.org
A Filipino Developers Community

>>> First two to make 3 wins! <<<

null check for strings
Strings are reference types and as such, they can have the value null.  If you have a method which accepts a string as its parameter, would you check the parameter for null or empty string and throw an ArgumentException instance if you expect a valid string instance to be passed into it? 

If it's not exposed as an API I wouldn't, it's pretty tedious for me since i expect all calls for the said method to pass a valid string instance since i trust my code.  Of course, i wouldn't have a unit test for it with an ArgumentException expectation for null and empty string which i now view as an overkill.

Posted 07-19-2006 10:31 PM by jokiz
Filed under: ,

Comments

cruizer wrote re: null check for strings
on 07-19-2006 4:04 PM
what I do is to create a static helper method, e.g. Util.GetStringValue() that I can use to get the string value of something, and have the method return something else (e.g. a String.Empty) if it's null. that way I do not get a null:

public static string GetStringValue(string s, string default)
{
  return (s != null) ? s : default;
}

public static string GetStringValue(string s)
{
  return GetStringValue(s, String.Empty);
}

or something like that.
jokiz wrote re: null check for strings
on 07-19-2006 6:39 PM
good idea!

Add it to the String class just like the static IsNullOrEmpty method.  i'll ask the bcl team, hehehe
Jop wrote re: null check for strings
on 07-19-2006 11:50 PM
I think it is easier to prevent my methods from passing invalid parameters than adding guard clauses for detecting them.

Only when the caller is not under my control do I add in the guard clauses.

If the method doesn't really care about the nullness of the parameter, then introducing a NullObject might be more worthwhile.
crawler486 wrote re: null check for strings
on 07-23-2006 10:13 PM
I use the good old ...

return object & "";

even if object is null, it will always return an empty string.

Copyright DevPinoy 2005-2008