Wednesday, May 14, 2008
OK people, for some reason this little gem has been overlooked by an awful lot of developers. Every time I see someone write an if statement that checks to see if a string is null, then if it is empty, I have to cringe. This static method on the String class is a very handy mechanism to do something that is extremely common in code I see.

instead of this

if (str == null || str == String.Empty)
{
    doSomething();
}


use this:


if (String.IsNullOrEmpty(str))
{
    doSomething();
}


It is so much cleaner, and faster too I think.

Just remember that this should probably be the first thing we write in the main line code after the second unit test is failing, for any method that takes a string parameter... [you know, the test where we send null in as the string parameter... then we have to write the if statement in the main code]. Which then follows closely with the third unit test in which we pass String.Empty as the value. But then again you already knew that. :-)

TDD | C#
Wednesday, May 14, 2008 7:21:24 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0]  |  Trackback
Comments are closed.
© Copyright 2014, John E. Boal