Java Reference
In-Depth Information
These different views provide a useful base from which to discuss questions such as:
How much checking should a server's methods perform on client requests?
How should a server report errors to its clients?
How can a client anticipate failure of a request to a server?
How should a client deal with failure of a request?
If we examine the AddressBook class with these issues in mind, we shall see that the class has
been written to trust completely that its clients will use it appropriately. Exercise 12.8 illustrates
one of the ways in which this is the case and how things can go wrong.
Exercise 12.8 Using the address-book-v1g project, create a new AddressBook object
on the object bench. This will be completely empty of contact details. Now make a call to its
removeDetails method with any string value for the key. What happens? Can you under-
stand why this happens?
Exercise 12.9 For a programmer, the easiest response to an error situation arising is to
allow the program to terminate (i.e., to “crash”). Can you think of any situations in which simply
allowing a program to terminate could be very dangerous?
Exercise 12.10 Many commercially sold programs contain errors that are not handled
properly in the software and cause them to crash. Is that unavoidable? Is it acceptable?
Discuss this issue.
The problem with the removeDetails method is that it assumes that the key passed to it is
a valid key for the address book. It uses the supposed key to retrieve the associated contact
details:
ContactDetails details = book.get(key);
However, if the map does not have that particular key, then the details variable ends up con-
taining null . That, of itself, is not an error; but the error arises from the following statement,
where we assume that details refers to a valid object:
book.remove(details.getName());
It is not allowed to call a method on a variable containing null , and the result is a runtime error.
BlueJ reports this as a NullPointerException and highlights the statement from which it
resulted. Later in this chapter, we shall be discussing exceptions in detail. For now, we can sim-
ply say that, if an error such as this were to occur in a running application, then the application
would crash—i.e., terminate in an uncontrolled way—before it had completed its task.
There is clearly a problem here, but whose fault is it? Is it the fault of the client object for calling
the method with a bad parameter value, or is it the fault of the server object for failing to handle
this situation properly? The writer of the client class might argue that there is nothing in the meth-
od's documentation to say that the key must be valid. Conversely, the writer of the server class
might argue that it is obviously wrong to try to remove details with an invalid key. Our concern
 
Search WWH ::




Custom Search