Code WTF? - 2011 edition
So today I was helping another developer who was running into some issues in production code - there is a file import that works fine up to a point, but for some reason, a particular file causes it grief.
As of this posting, we still haven’t found the problem - but during lunch, I had to post what we DID find!
As we were debugging through the parsing library, I ran into a bit of code written by Random Developer. At first caught it me off guard, then left me quite literally, Laughing Out Loud.
It starts out simple enough - even has a comment:
1:
2: /// <summary>Parses a String to a bool</summary>
3: public static bool Bool<T>(this T value)
4: {
Not bad - I think that for this particular process, the Generic is probably overkill - but we will go with it:
Next, lets parse this thing up:
1: if (value == null || value.ToString().Length == 0) return false;
2: try { return Convert.ToBoolean(value); }
3: catch { }
First, if you are using Generics, you have a .NET framework that supports TryParse on all the types **. Yes, a TryParse is a bit more convoluted and requires the use of a generally misunderstood Out parameter - Oh, and a HUGE performance increase if you are parsing a value that fails.
But I’ll over-look that for now, because it is just a sign of what is to come…
So, assuming that the above parse didn’t actually return a properly parsed value, Random Developer decided to add an extra bit of code:
1: string testValue = value.ToString();
2: if (testValue.Empty()) return false;
Uh, OK - seems a bit redundant to me - but we haven’t gotten to the best (and LOL) part yet:
Our friend, Random Developer decided to check this value that didn’t parse into a Boolean against a list of 'Yeses' - Huh? List of Yeses?
1: var yeses = new List<string> { "1", "true", "yes", "y", "yeah",
2: "yea", "ya", "yo", "yesh", "indeed",
3: "uhuh", "yep", "yah", "damnstraight",
4: "valid", "damn skippy", "you betcha",
5: "bobs your uncle", "all right", "ok",
6: "sure", "why not", "of course", "agreed",
7: "fair enough", "absolutely", "right",
8: "if i have too" };
9: return yeses.Contains(testValue.ToLower());
Yep, Bob’s your Uncle, You Betcha, Damn Skippy - if it is one of these values, it must mean it is TRUE!
At least they used ToLower().
So, Random Developer - you officially made my year on my random code WTF?!
** It also supports String.IsNullOrEmpty - but that’s just a personal preference - instead of individually checking for Null and no Length…