The Daily Parker

Politics, Weather, Photography, and the Dog

Pop quiz: Why does this code fail?

Here's some code I discovered while tracking a bug this morning:

const string DATE_FORMAT = "M/d/yyyy";

string dateString = 
   ConfigSettings.GetString("Some setting", DateTime.Now.ToString(DATE_FORMAT));

DateTime someDate = 
   DateTime.ParseExact(dateString, DATE_FORMAT, CultureInfo.InvariantCulture);

The DateTime.ParseExact method throws a FormatException if the string (dateString) doesn't exactly match the format string. I mean, exactly. So when dateString comes back from the configuration settings class as "5-12-2006" (instead of "5/12/2006"), guess what happens.

My correction:

DateTime someDate = DateTime.Parse(dateString, CultureInfo.InvariantCulture);

The DateTime.Parse method takes any legal input and attempts to parse it, freeing the developer from having to know what formats may occur. The DateTime.ParseExact method has some specific applications, but when you don't know what you're getting, it's risky—especially when you don't actually catch the FormatException anywhere.

Of course, the DateTime.Parse method could also throw a FormatException. In the code I'm debugging, since the date isn't really coming from a configuration set that we control and is, in fact, coming from an unknown third party[1], I'm actually going to go with an even more forgiving option:

string dateString = ConfigSettings.GetString("Some setting", string.Empty);

DateTime someDate;
if (DateTime.TryParse(dateString, someDate) == false)
   someDate = DateTime.Now;

Moral: Never assume anything about inputs you don't directly control.

[1] You could tell all that from the name of the class, right? I mean, if you see something called "ConfigSettings" you kind of assume that the class has something to do with configuration settings, and doesn't have anything to do with talking to computers in Ohio, right? I'm not making this up: the method call in question may go to Ohio for its data. This highlights the importance of naming your classes correctly so that people trying to use your code don't curse your name unto the generations.

Comments are closed