ApexSensei

Drills › Think in classes

Expose a read-only quote total

Think in classes · Intermediate · 15 min · Runs in your Salesforce Developer org · Free

Scenario. A renewal service should reveal its calculated total without letting callers overwrite that result.

Use Apex properties to protect a subtotal and work out a read-only total with tax.

What you will learn

Properties expose a value through get and set. With private set, other classes can read the value but only this class can change it. A getter with a body works out its value each time it is read.

public Decimal amount { get; private set; }
public Decimal doubled {
    get {
        return amount * 2;
    }
}

Gotcha. A getter can run many times. Keep it free of side effects like DML. A script like this one can still reach a private setter; deployed classes enforce it.

The task

Build a renewal quote whose protected subtotal drives a read-only total with 8% tax.

Examples:

  • subtotal 100.00 → Initial total: 108.00
  • after changeSubtotal(250.00) → Updated total: 270.00
  • subtotal 0.00 → Zero subtotal: 0.00

Requirements:

  1. Keep subtotal readable by anyone, with a private setter.
  2. Give total a getter only (no setter) that returns subtotal plus 8% tax, rounded to 2 places with setScale(2, RoundingMode.HALF_UP).
  3. Make changeSubtotal update the subtotal.
  4. Print Initial total:, then change the subtotal to 250.00 with changeSubtotal and print Updated total:. Read both from quote.total. Never assign quote.subtotal from outside the class.
  5. Print Zero subtotal: from a second quote built with 0.00.

Starter code

class RenewalQuote {
    public Decimal subtotal { get; private set; }

    public Decimal total {
        get {
            return 0;
        }
    }

    public RenewalQuote(Decimal subtotal) {
        this.subtotal = subtotal;
    }

    public void changeSubtotal(Decimal newSubtotal) {
    }
}

RenewalQuote quote = new RenewalQuote(100.00);

When it passes

The total is always worked out from the protected subtotal, including after a change and at zero.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Protect a support ticket subject · Overload a Case label method ›