CodeSOD: A Terned Around Discount
If you browse the Errords, it's easy to see that "giving customers a discount" is apparently harder than it looks.
Brian's company had one of those "discounts are hard" problems, way back when. Sometimes instead of a discount reducing the price, it would raise it. The root cause was that the sales team setting up the promotions weren't clear about whether the discount amount should be a negative or positive number. Instead of adding validation to ensure they always entered a negative (or at least, a zero amount), one of Brian's predecessors fixed the bug in their C# like this:
PromotionDiscount = n.PromotionAmount.ToString()[0] == '-' ? n.PromotionAmount.ToString() : n.PromotionAmount.ToString() == "0" ? n.PromotionAmount.ToString() : "-" + n.PromotionAmount.ToString()
Line-breaks added.
So, problem the first, of course, is that the input should have been validated so that everything happening here is unnecessary. Problem the second is that this code is meant to be taking any discounts that are greater than zero, and making them negative, and decides to do this through string manipulation. PromotionAmount is already a numeric type, so if n.PromotionAmount > 0... could do the job, or if you really want a one-liner, Math.abs(n.PromotionAmount) * -1.
Then, of course, it's all topped with a nested ternary. It's at least a short one, but it adds a wonderful something extra. Code that doesn't need to exist, implemented in the most awkward way, with a bonus of unreadability.
[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!