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.
dasBlog theme by Mads Kristensen
Watch Parker, um, sleep whenever I remember to point the camera at him. Updated every 60 seconds.
Only 59 days, 23 hours, and 31 minutes remain until the Obama Administration.
All content Copyright ©2008 David Braverman. All rights reserved.
Disclaimer This blog contains the personal opinions of David Braverman and, where applicable, guest bloggers.