Contacts – Part 3
Goal: Quality control the Contact
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 the caller invokes a method at a bad time (object not in a valid state).
Throwing an unchecked exception forces the caller to improve their code.
Task 1 – Contact
Constructor
In the Contact
constructor, throw an IllegalArgumentException
if the:
-
name
isnull
ORblank
. -
phoneNumber
isnull
ORblank
. -
phoneNumber
length is less than 5.
Should the constructor throw an IllegalArgumentException
if birthDate
is null
OR blank
?
- Not necessary. The underlying
parse()
method already throws a checked exception if thebirthDate
is not parseable.
Task 2 – setName
Inside setName
, throw an IllegalArgumentException
if the caller passes a name
that is blank
or null
.
Task 3 – setPhoneNumber
Inside setPhoneNumber
, throw an IllegalArgumentException
if:
-
the caller passes a
phoneNumber
that isblank
ornull
. -
the
phoneNumber
is less than 5 characters.
Task 4 – setBirthDate
-
Should we throw an
IllegalArgumentException
ifbirthDate
isnull
ORblank
?- Not necessary. The setter already throws an exception if the
birthDate
is not parseable. Throwing another one is redundant.
- Not necessary. The setter already throws an exception if the
That's all!
You added checkpoints to the Contact
class
. Each checkpoint forbids the caller from misusing the methods/constructors.