Java Reference
In-Depth Information
Code 12.3
continued
A boolean return type
to indicate success or
failure
* @return true if the entry was successfully removed,
* false otherwise.
*/
public boolean removeDetails(String key)
{
if (keyInUse(key)) {
ContactDetails details = book.get(key);
book.remove(details.getName());
book.remove(details.getPhone());
numberOfEntries--;
return true ;
}
else {
return false ;
}
}
This allows a client to use an if statement to guard statements that depend on the successful
removal of an entry:
if(contacts.removeDetails("...")) {
// Entry successfully removed. Continue as normal.
...
}
else {
// The removal failed. Attempt a recovery, if possible.
...
}
Where a server method already has a non- void return type—effectively preventing a boolean
diagnostic value from being returned—there may still be a way to indicate that an error has
occurred through the return type. This will be the case if a value from the return type's range is
available to act as an error diagnostic value. For instance, the getDetails method returns a
ContactDetails object corresponding to a given key, and the example below assumes that a
particular key will locate a valid set of contact details:
// Send David a text message.
ContactDetails details = contacts.getDetails("David");
String phone = details.getPhone();
...
One way for the getDetails method to indicate that the key is invalid or not in use is to have
it return a null value instead of a ContactDetails object (Code 12.4).
Code 12.4
Returning an out-of-
bounds error diagnostic
value
/**
* Look up a name or phone number and return the
* corresponding contact details.
* @param key The name or number to be looked up.
 
Search WWH ::




Custom Search