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)
{
    
    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!

Remy Porter

Source link

You May Also Like

Remembering Robbie Coltrane with some hilarious Hagrid Memes (18 Photos)

Matthew Source link

Sean Hannity Says He’d Use MMA Skills To Protect Himself In A Mass Shooting

Fox News host Sean Hannity used the devastating Lewiston shooting to bring…

Onion Sports’ NFL Wild Card Weekend Picks

Read more… Source link

Mac ’n CHEESY morning memes (31 Photos)

Rick Source link