Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 11 / Topic 4 of 9

The discount module

src/main/kotlin/com/stepshala/billing/DiscountCalculator.kt — the membership/coupon/GST logic from Stage 1's discount calculator (Part 5), now living as its own tested module instead of inline in a main():

fun membershipDiscountPercent(tier: String): Double = when (tier.lowercase()) {
    "gold" -> 15.0
    "silver" -> 10.0
    "regular" -> 0.0
    else -> throw IllegalArgumentException("Unknown membership tier: $tier")
}

fun finalBill(
    subtotal: Double,
    membershipDiscountPercent: Double,
    couponPercent: Double = 0.0,
    applyGst: Boolean = true
): Double {
    require(subtotal >= 0.0) { "subtotal cannot be negative, got $subtotal" }
    require(membershipDiscountPercent in 0.0..100.0) {
        "membershipDiscountPercent must be 0..100, got $membershipDiscountPercent"
    }
    val safeCoupon = couponPercent.coerceIn(0.0, 100.0)
    val afterMembership = subtotal - subtotal * membershipDiscountPercent / 100
    val afterCoupon = afterMembership - afterMembership * safeCoupon / 100
    return if (applyGst) afterCoupon * 1.18 else afterCoupon
}

Two choices worth noticing, both made because this code is about to be unit tested: membershipDiscountPercent for an unknown tier throws instead of silently returning 0.0 (a test can assert on that), and finalBill validates its own inputs with require instead of trusting the caller — both give the test suite in section 5 something real to check.

Full file: examples/project-layout/src/main/kotlin/com/stepshala/billing/DiscountCalculator.kt.

Done here? The practice set for Part 11 — including the solutions — is on the part page.

Search the guide