CodeSOD: Trying Parses

Another day, another terrible way to validate integers. Today's submission comes from Sluiper.

This approach, at least, contains a mild bit of cleverness. It's not the good kind of cleverness that makes a complicated problem more clear and easier to understand, but the bad kind that exploits assumptions about low-level technical details.

private static bool IsInteger(string pString)
{
	for (int i = pString.Length - 1; i >= 0; i--)
	{
		if (pString[i] > '9' || pString[i] < '0')
		{
			return false;
		}
	}
	return true;
}

In this case, we exploit the fact that almost all character sets put the characters 0-9 adjacent to each other in sequence. Not that C# support EBCDIC, but even EBCDIC obeys that common-sense rule. EBCDIC doesn't put letter characters adjacent to each other, but it at least puts digits all together in a group.

I also appreciate the reverse string traversal, as a pointless micro-optimization. I can see the developer looking at the real world data they need to validate, seeing that the last few characters were usually the ones that would break validation, and opting to traverse backwards to save a few comparison operations.

It's that last optimization that's notable, just because the basic algorithm showed up here in 2005- but in PHP. I hope and fear that some developer ported the PHP version to C# because they couldn't find a better option.

Of course, all that effort, and they ignored the built-in TryParse. Ah well.

[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published. Required fields are marked *