Going through TDWTF inbox, I’ve built a sort of mental taxonomy of bad code. For example, there’s the kingdom of Tempus Malum: home-brew date manipulation functions, a rather profligate branch of bad code. Or the Order of Linguan Ignorans- bad code developed out of a complete ignorance of the available language features.
There’s another category that I always consider a treat. It’s related to Linguan Ignorans, but also borrows from Quaesto Ignorat (ignorant of the problem being solved): Filo Annexa, or “Knotted String”, also known as “String All the Things!”
Which brings us to today’s C# code, from Aaron.
public string ShortenFloatString(float valueToShorten)
{
string xString;
string xString2 = "";
xString = valueToShorten.ToString();
if (xString.IndexOf('.') > -1)
xString2 = xString.Substring(xString.IndexOf('.'));
if (xString2.Length > 3)
xString2 = xString2.Substring(0, 3);
if (xString.IndexOf('.') > -1)
xString = xString.Substring(0, xString.IndexOf('.'));
if(xString2.Length > 2)
{
if(xString2[2] == '9')
{
int num = int.Parse(xString2[1].ToString());
if (num <= 9)
{
num++;
xString2 = "." + num.ToString();
}
else
{
num = 0;
xString2 = "." + num.ToString();
int firstNum = int.Parse(xString);
firstNum++;
xString = firstNum.ToString();
}
}
}
return (xString + xString2);
}
I’ve never had to spend so much time looking at a rounding function to confirm that it is, in fact, a rounding function. Well, sort of. It doesn’t enforce any rounding rule that I’ve ever heard of.
Like all bad code, it eschews the built in functions for solving this problem. But it takes it to another level, by doing all the rounding through string manipulation- at least as much as it can. Strings, of course, can’t be effectively rounded, so of course there’s a moment where we need to int.Parse
bits of the strings back into numbers so that we can actually do rounding.
Bonus points are awarded for excellent variable names, and also for using Substring
instead of Split
, which is also a built-in method.