Solution to a22c: No duplicate email addresses
See code at solutions/code/tutorialquestions/questiona22c
In package checkforduplicates I have defined an exception class:
DuplicateEmailAddressException
This class extends Exception, meaning that it is a checked exception.
I have equipped the EmailAddress class with a static field:
private static Set<String> pastIdentifiers = new HashSet<String>();
storing identifiers that have previously been used in email addresses. The constructor of EmailAddress first checks whether the given
identifier is in this set. If it is, a DuplicateEmailAddressException is thrown. As a result, the signature of the EmailAddress
constructor is:
public EmailAddress(String identifier) throws DuplicateEmailAddressException;
Because the constructors of IndividualEmailAddress and GroupEmailAddress both call the constructor of EmailAddress, these constructors are also declared as throwing DuplicateEmailAddressException.
Demo shows this exception being thrown in practice: the identifier wayne@doc.ic.ac.uk is used in the creation of two different
email addresses.
Advanced: The package checkforcycles includes another exception class:
CyclicEmailGroupException
This is an uncaught exception (a.k.a.~a runtime exception), because a good programmer should simply be careful not to create cyclic email group relationships. It would be a pain
to have to enclose all email address operations in try...catch blocks simply because of the possibility of cycles being introduced.
The addEmailAddress method of GroupEmailAddress uses helper method reaches to determine whether the email address
being added to the group itself contains a chain of email addresses that includes the group. Inspect reaches and check that you understand it.
If reaches returns true then adding this email address would create a cycle, so instead a CyclicEmailGroupException is added. Demo provides an illustration of this exception being thrown in practice.