Shopping Cart – Part 5
Goal: Quality control the Cart
class.
Unchecked exceptions
An unchecked exception crashes the app as a result of badly written code.
You should throw an:
-
IllegalArgumentException
when the caller passes faulty arguments into a method/constructor. -
IllegalStateException
when an object calls its method at a "bad time" (object not in a legal state).
Throwing an unchecked exception forces the caller to improve their code.
Task 1 – Inspecting the Cart
class
-
The constructor doesn't receive any parameters so there's nothing to check.
-
Should the
setItem
setter check for anull
? No.- The code would already throw a
NullPointerException
. So, throwing anIllegalArgumentException
would be redundant.
- The code would already throw a
-
Should the
add
method check for anull
? No.- For the same reason as before.
-
Should the
remove
method check for anull
? No.- For the same reason as before.
-
Is there a need to throw an
IllegalStateException
anywhere? Yes, in two places.
-
If the
items
ArrayList
is empty, the store is not in a valid state to call theremove
method. -
If the
items
ArrayList
is empty, the store is not in a valid state to call thecheckout
method.
That's all!
You added checkpoints to the Cart
class. The checkpoints forbid the caller from misusing the remove
and checkout
methods.