Lesson 8 of 8
Fail fast
- 12 min
- 5 checks
- 3 hints
- Go to task
Goal
The error shows up at its cause, not after it
Explanation
The worst bugs are the ones that show up far from their cause. A 150% discount produces a negative price, that price passes through three functions, and it finally lands on the invoice with nobody knowing where it came from.
An invariant is a condition that must always hold, like a price being a non-negative number or a percentage being between 0 and 100. The function assert(condition, message) checks that condition at the top of a function and throws an error right away if it doesn't hold, so the error shows up at its cause, not three steps later.
The error message is half the fix. "Invalid value" helps nobody, but a message that says what was expected and what actually came in tells whoever reads it where to look from the very first line.
Your task
Write assert(condition, message) so it throws an Error with the given message when the condition is false. Then use it at the top of applyDiscount to make sure the price is a non-negative number and the percentage is between 0 and 100, with both limits allowed, and make the percentage message mention the value it received.
Checks
5 checks- assert does nothing when the condition holds
- assert throws an Error with its message when the condition fails
- A percentage over 100 is rejected with a message that names it
- An invalid price is rejected
- Valid inputs pass and both limits are allowed