Friday, September 28, 2012

On "clever".

Recently I came across some odd behaviour in a web system around date and time parsing. There was a validation step responsible for ensuring one date/time value was greater than the other. But it seemed to trip up in certain scenarios, such as around 08:00 in the morning. (Anyone used to working with Javascript probably knows exactly what the problem is already.:)

Fortunately I'd come across the cause of this bug a short time ago when enhancing a Javascript-based date parser.

Someone responsible for Javascript's parseInt() method thought it would be clever to try and determine what kind of numeric value was being passed in by inspecting the string and choosing an appropriate conversion rule. (I've read this may be a carry over from C, but regardless it is a stupid assumption that should never have been propagated.) If you pass in "0x..." it can be assumed you want to do a Hex conversion. Fair enough. But then they assumed that if you passed in a value with just a leading 0(zero) you'd want to do an Octal conversion.

I'm sorry, but this has to be one of the dumbest assumptions I've ever seen and surely has led to, and will continue to lead to countless bugs throughout the history of web applications. It's an absolutely stupid assumption because in either Octal or Decimal, 00-07 will result in: 0 - 7. The fun bit is that if you pass parseInt "08" or "09", you get back: wait for it, #null. Pass it "10" and the logic switches to assume you mean Decimal, so it passes you back 10.

So yes, according to parseInt, when you want to check a month number, your calendar must be:
January, Febuary, March, April, May, June, July, #null, #null, October, November, December.

So, if you're encountering unexplained bugs first thing in the morning, or with data for August or September be sure to inspect any and all parseInt calls.

parseInt("08", 10);

Someone owes an apology to the countless developers handed a #null for "08" and "09", and the possible *single* developer wondering where his 9 went after being led to believe parseInt defaulted to Octal.

No comments:

Post a Comment