Java Reference
In-Depth Information
in this chapter is not to resolve such disputes, but to try to prevent them from arising in the first
place. We shall start by looking at error handling from the point of view of the server class.
Exercise 12.11 Save a copy, to work on, of one of the address-book-v1 projects
under another name. Make changes to the removeDetails method to avoid a
NullPointerException arising if the key value does not have a corresponding entry in the
address book. Use an if statement. If the key is not valid, then the method should do nothing.
Exercise 12.12 Is it necessary to report the detection of an invalid key in a call to remove-
Details ? If so, how would you report it?
Exercise 12.13 Are there any other methods in the AddressBook class that are vulnerable
to similar errors? If so, try to correct them in your copy of the project. Is it acceptable in all cases
for the method simply to do nothing if its parameter values are inappropriate? Do the errors need
reporting in some way? If so, how would you do it, and would it be the same way for each error?
12.2.2 Parameter checking
A server object is most vulnerable when its constructor and methods receive external values
through their parameters. The values passed to a constructor are used to set up an object's ini-
tial state, while the values passed to a method will be used to influence the overall effect of the
method call and may change the state of the object and a result the method returns. Therefore, it
is vital that a server object knows whether it can trust parameter values to be valid or whether it
needs to check their validity for itself. The current situation in both the ContactDetails and
AddressBook classes is that there is no checking at all on parameter values. As we have seen
with the removeDetails method, this can lead to a fatal runtime error.
Preventing a NullPointerException in removeDetails is relatively easy, and Code 12.2
illustrates how this can be done. Note that, as well as improving the source code in the method,
we have updated the method's comment, to document the fact that unknown keys are ignored.
Code 12.2
Guarding against an
invalid key in
* Remove the entry with the given key from the address book.
* If the key does not exist, do nothing.
* @param key One of the keys of the entry to be removed.
public void removeDetails(String key)
if (keyInUse(key)) {
ContactDetails details = book.get(key);
Search WWH ::

Custom Search