1
\$\begingroup\$

refundableSale is a PMSale object with properties refundableTip, refundableTax and refundableSubtotal. The requestRefundFor method takes a total refund amount as argument along with the refundable sale.

The requirement is you should first refund from the tips, then from the tax and then from the subtotal, if needed.

The flow works like this:

  1. Refund the requested amount from tips
  2. If there's more amount to refund, refund from tax next
  3. If there's even more amount to refund, refund from subtotal

As you can see, my implementation of this has a lot of duplicate lines that I want to get rid of.

func requestRefundFor(amount refundAmount: NSDecimalNumber, sale refundableSale: PMSale) {
    var refundRequestedAmount = refundAmount

    var tipAmountToRefund = NSDecimalNumber.zero()
    var taxAmountToRefund = NSDecimalNumber.zero()
    var subtotalAmountToRefund = NSDecimalNumber.zero()

    if refundRequestedAmount.isGreaterThanOrEqualTo(refundableSale.refundableTip) {
        refundRequestedAmount = refundRequestedAmount.decimalNumberBySubtracting(refundableSale.refundableTip)
        tipAmountToRefund = refundableSale.refundableTip

        if refundRequestedAmount.isGreaterThanOrEqualTo(refundableSale.refundableTax) {
            refundRequestedAmount = refundRequestedAmount.decimalNumberBySubtracting(refundableSale.refundableTax)
            taxAmountToRefund = refundableSale.refundableTax

            if refundRequestedAmount.isGreaterThanOrEqualTo(refundableSale.refundableSubtotal) {
                refundRequestedAmount = refundRequestedAmount.decimalNumberBySubtracting(refundableSale.refundableSubtotal)
                subtotalAmountToRefund = refundableSale.refundableSubtotal

            } else {
                subtotalAmountToRefund = refundRequestedAmount
            }
        } else {
            taxAmountToRefund = refundRequestedAmount
        }
    } else {
        tipAmountToRefund = refundRequestedAmount
    }

    requestRefund(sale: refundableSale, subtotalRefundAmount: subtotalAmountToRefund, tip: tipAmountToRefund, tax: taxAmountToRefund)
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.