"To Be [null], or Not To Be [null]," says the String

By Michael Flanakin @ 3:46 PM :: 1232 Views :: .NET, Development :: Digg it!

String Handling

David Kean Syndicated feed mentions his thoughts on string handling and I have to say I completely disagree. He states that you should always return String.Empty instead of null. I hate this. An empty string and what equates to "no value," by definition, mean two different things. David, on the other hand, contends that the two should always be treated as the same. To be clear, I'm not saying the two should never be handled the same. On the contrary, I believe that's the norm... and rightfully so. With that, however, there are still cases where they need to be handled differently. Besides, the benefits you get from returning an empty string are immediately invalidated when considering consistency principles.

I'd even go as far as to say, returning empty strings promotes bad practices. Why? Because the developer then treats what is returned as a non-null value. While this isn't a problem, it typically goes further. The same developer will start assuming all methods that return strings act the same way. Let's not forget what they say about people who make assumptions... For this reason, I believe it's a good practice to always use String.IsNullOrEmpty() to validate string values, no matter what you think/know is returned.

I could list a number of what-if scenarios depicting why this is so important, but I won't. It should be pretty clear. Let's face it, we've all fallen victim to a null reference exception, which is essentially what happens when you assume a variable has a value. Clarify your assumptions with good exception handling.

Lastly, one other reason I like null over empty strings is because it uses less memory. Yes, this is very trivial, but it's true. The bottom line is that, whether you return null or empty string, you have to treat it as if it were null. For this reason alone, I believe it's cleaner to simply use null. Using empty strings is a hack, in my mind, unless it really means something different than "no value."

 

Ratings