-4

I'm calculating the displayed payment amount for an order receipt, I want to reduce those conditions to the max:

private double CalculateFinalTotal(bool hasPrommoCode, 
                                   double promoCodeValue, 
                                   double finalTotal, 
                                   double? tip)
{
    if (!hasPrommoCode) return finalTotal;
    if (promoCodeValue > finalTotal && tip.HasValue) return tip.Value;
    else if (promoCodeValue > finalTotal) return 0;
    else if (tip.HasValue)
    {
        var totalWithoutTip = finalTotal - tip.Value;
        return (totalWithoutTip > promoCodeValue ? totalWithoutTip - promoCodeValue : 0) + tip.Value;
    }
    else return finalTotal - promoCodeValue;
}
Ahmed Sherien
  • 313
  • 1
  • 2
  • 15

1 Answers1

2

First of all, never use double for money-related code, always use decimal.

Besides that, you can omit checking whether tip has a value or not using GetValueOrDefault(). And, following c# conventions (if you actually care about readability), always use brackets around if statements.

You should end up with something like:

private decimal CalculateFinalTotal(bool hasPrommoCode, decimal promoCodeValue, 
                                   decimal finalTotal, decimal? tip)
{
    if (!hasPrommoCode) 
    {
        return finalTotal;
    }

    if (promoCodeValue > finalTotal) 
    {
        // if .HasValue == true => return .Value; otherwise return 0
        return tip.GetValueOrDefault();
    }

    if (tip.HasValue)
    {
        var totalWithoutTip = finalTotal - tip.Value;
        return (totalWithoutTip > promoCodeValue ? totalWithoutTip - promoCodeValue : 0) + tip.Value;
    }

    return finalTotal - promoCodeValue;
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120