Java Reference
In-Depth Information
Exercise 12.38 Suppose that we decide to allow the address book to be indexed by
address as well as name and phone number. If we simply add the following statement to the
addDetails method
book.put(details.getAddress(), details);
do you anticipate that any assertions will now fail? Try it. Make any further necessary changes
to AddressBook to ensure that all of the assertions are now successful.
Exercise 12.39 ContactDetails are immutable objects—that is, they have no muta-
tor methods. How important is this fact to the internal consistency of an AddressBook ?
Suppose the ContactDetails class had a setPhone method, for instance? Can you
devise some tests to illustrate the problems this could cause?
12.7.4
Assertions and the BlueJ unit-testing framework
In Chapter 7, we introduced the support that BlueJ provides for the JUnit unit-testing
framework. That support is based on the assertion facility we have been discussing in this
section. Methods from the framework, such as assertEquals , are built around an asser-
tion statement that contains a boolean expression made up from their parameters. If JUnit
test classes are used to test classes containing their own assertion statements, then assertion
errors from these statements will be reported in the test-results window along with test-
class assertion failures. The address-book-junit project contains a test class to illustrate
this combination. The testAddDetailsError method of AddressBookTest will trigger
an assertion error, because addDetails should not be used to change existing details (see
Exercise 12.33).
12.8
Error recovery and avoidance
So far, the main focus of this chapter has been on the problem of identifying errors in a server
object and ensuring that any problem is reported back to the client if appropriate. There are two
complementary issues that go with error reporting: error recovery and error avoidance.
12.8.1 Error recovery
The first requirement of successful error recovery is that clients take note of any error notifica-
tion that they receive. This may sound obvious, but it is not uncommon for a programmer to
assume that a method call will not fail and so not bother to check the return value. While ignor-
ing errors is harder to do when exceptions are used, we have often seen the equivalent of the
following approach to exception handling:
AddressDetails details = null;
try {
details = contacts.getDetails(...);
}
 
 
Search WWH ::




Custom Search