CodeSOD: No Percentage In It

James was asked to investigate some legacy code for the sole purpose of figuring out how to replace it. There were all sorts of bad blocks in there, but this one caught James's eye as being notable.

And it is. This code has a simple job: given an old value and a new value, tell us the difference as a percentage of the old value. You or I might write this as a one-liner, but this clever developer is on an entirely different level:

private decimal GetPercentChange(decimal oldValue, decimal newValue)
{
    // Enforcing negative and positive to emphasize direction of percent change.
    if (newValue > oldValue)
        return Math.Abs((newValue - oldValue) / oldValue);
    else if (newValue < oldValue)
        return -1 * Math.Abs((oldValue - newValue) / oldValue);
    else return 0m;
}

James showed this to a co-worker, who responded: "You've heard of long division, but have you ever heard of long subtraction?"

"Enforcing negative and positive to emphasize direction of percent change", indeed. If only there were some way to subtract two numbers and get a negative result if the second operand was larger. Pity that's not how subtraction works.

Wait, no, that's exactly how subtraction works. James replaced this all with a single line: return (newValue - oldValue) / Math.Abs(oldValue).

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!

This post originally appeared on The Daily WTF.

Leave a Reply

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