Java Reference
In-Depth Information
Code 12.4
continued
Returning an out-of-
bounds error diagnostic
value
* @return The details corresponding to the key, or
* null if the key is not in use.
*/
public
ContactDetails getDetails(String key)
{
if
(keyInUse(key)) {
return
book.get(key);
}
else
{
return
null
;
}
}
This would allow a client to examine the result of the call and then either continue with the
normal flow of control or attempt to recover from the error:
ContactDetails details = contacts.getDetails("David");
if(details != null) {
// Send a text message to David.
String phone = details.getPhone();
...
}
else {
// Failed to find the entry. Attempt a recovery, if possible.
...
}
It is common for methods that return object references to use the
null
value as an indication of
failure or error. With methods that return primitive-type values, there will sometimes be an
out-
of-bounds value
that can fulfill a similar role: for instance, the
indexOf
method of the
String
class returns a negative value to indicate that it has failed to find the character sought.
Exercise 12.18
Do you think the different interface styles of the
v2t
and
v2g address-book
projects mean that there should be a difference in the way errors are reported to users?
Exercise 12.19
Using a copy of the
address-book-v2t
project, make changes to the
AddressBook
class to provide failure information to a client when a method has received
incorrect parameter values or is otherwise unable to complete its task.
Exercise 12.20
Do you think that a call to the
search
method that finds no matches
requires an error notification? Justify your answer.
Exercise 12.21
What combinations of parameter values would it be inappropriate to pass
to the constructor of the
ContactDetails
class?
Search WWH ::
Custom Search