Article 4DMT4 CodeSOD: Be True to Yourself

CodeSOD: Be True to Yourself

by
Remy Porter
from The Daily WTF on (#4DMT4)

Ben M recently inherited some code from some Highly Paid Consultants. These consultants needed to be able to set some flags to control the behavior of the application, and for whatever reason, these flags needed to be strings. It probably wasn't a good reason, but there was some reason. The consultants wrote the module which set the flags, and guaranteed that the flags were only ever "true" or "false".

To parse those flags back into boolean values, they did it the true Highly Paid Consultant way: they used a generic "string to boolean" solution they copied from Stack Overflow instead of Boolean.Parse, the built-in C# method for turning "true" into a boolean value.

private bool ConvertBoolean(string value, bool defaultValue = false){ bool returnValue = defaultValue; if (value == null) { return returnValue; } if ("y".Equals(value, StringComparison.OrdinalIgnoreCase) || "yes".Equals(value, StringComparison.OrdinalIgnoreCase) || "true".Equals(value, StringComparison.OrdinalIgnoreCase) || "1".Equals(value, StringComparison.OrdinalIgnoreCase) || "on".Equals(value, StringComparison.OrdinalIgnoreCase)) { returnValue = true; } else if ("n".Equals(value, StringComparison.OrdinalIgnoreCase) || "no".Equals(value, StringComparison.OrdinalIgnoreCase) || "false".Equals(value, StringComparison.OrdinalIgnoreCase) || "0".Equals(value, StringComparison.OrdinalIgnoreCase) || "off".Equals(value, StringComparison.OrdinalIgnoreCase)) { returnValue = false; } return returnValue;}

Finally, this tells us the true value of FILE_NOT_FOUND, which is to say, whatever we passed in for our defaultValue, because that's what happens if this code doesn't understand how to parse the string.

buildmaster-icon.png [Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today! TheDailyWtf?d=yIl2AUoC8zAcg9Z7riwxho
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments