ApexSensei

Drills Security & deployment

Gate work behind a feature flag

Security & deployment · Intermediate · 12 min · Runs in your Salesforce Developer org · Apex Path

Write `priceAfterFlags` so a `promo` flag applies a 10 percent discount. A missing key, a false flag, or a null map leave the amount unchanged. A null amount returns 0. Round the discount with integer division, `(amount * 9) / 10`, which drops the remainder.

Lesson

Why this matters

A feature flag should turn work on only when it is explicitly true. A missing key, a false flag, and a null map all mean off. A null amount has to be handled before you multiply. Integer division drops the remainder, so a 10 percent discount is (amount * 9) / 10.

The smallest working example

if (amount == null) {
    return 0;
}
if (flags != null && flags.get('promo') == true) {
    return (amount * 9) / 10;
}
return amount;

100 with promo on returns 90. Anything else returns the amount, or 0 when the amount is null.

Name the parts

  • **flags.get('promo')** returns null when the key is missing.
  • **== true** is false for both false and null, so a missing flag stays off.
  • **flags != null** comes first, because get on a null map throws.
  • **(amount * 9) / 10** is integer division. 95 becomes 85, not 85.5.

A common wrong version

if (flags.get('promo')) {
    return (amount * 9) / 10;
}
return amount;

A null map throws on get. A missing key makes the if test a null Boolean, which throws. A null amount throws when you multiply.

The fix

Return 0 when amount is null. Return amount unless the map exists and promo is exactly true. Then apply (amount * 9) / 10.

Now you try

Write priceAfterFlags. Keep the signature. Promo on 100 is 90, promo off is 100, a null amount is 0, and an empty map leaves the amount alone.

Learn more

The challenge

Write priceAfterFlags(Integer amount, Map<String, Boolean> flags) so a promo flag applies a 10 percent discount.

Examples:

  • priceAfterFlags(100, promo true) → 90
  • priceAfterFlags(100, promo false) → 100
  • priceAfterFlags(null, promo true) → 0

Requirements:

  1. priceAfterFlags(100, promo true) should be 90.
  2. priceAfterFlags(100, promo false) should be 100.
  3. priceAfterFlags(null, promo true) should be 0.
  4. priceAfterFlags(50, empty flags) should be 50.

Starter code

Integer priceAfterFlags(Integer amount, Map<String, Boolean> flags) {
    return null;
}

Related drills

Try this drill free

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

‹ User-mode DML with `insert as user` · Choose a deploy test level ›