CodeSOD: No Percentage In It

This post was originally published on this site

The Daily WTF

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

To read the full article click on the 'post' link at the top.