Java Reference
In-Depth Information
Code 12.17
Checking for internal
consistency in the
address book
/**
* Check that the numberOfEntries field is consistent with
* the number of entries actually stored in the address book.
* @return true if the field is consistent, false otherwise.
*/
private boolean consistentSize()
{
Collection<ContactDetails> allEntries = book.values();
// Eliminate duplicates, as we are using multiple keys.
Set<ContactDetails> uniqueEntries =
new HashSet<ContactDetails>(allEntries);
int actualCount = uniqueEntries.size();
return numberOfEntries == actualCount;
}
12.7.3
Guidelines for using assertions
Assertions are primarily intended to provide a way to perform consistency checks during the
development and testing phases of a project. They are not intended to be used in released code.
It is for this reason that a Java compiler will include assert statements in the compiled code only
if requested to do so. It follows that assert statements should never be used to perform normal
functionality. For instance, it would be wrong to combine assertions with removal of details, as
follows, in the address book:
// Error: don't use assert with normal processing!
assert book.remove(details.getName()) != null;
assert book.remove(details.getPhone()) != null;
Exercise 12.35 Open the address-book-assert project. Look through the AddressBook
class and identify all of the assert statements to be sure that you understand what is being
checked and why.
Exercise 12.36 The AddressBookDemo class contains several test methods that call
methods of AddressBook that contain assert statements. Look through the source of
AddressBookDemo to check that you understand the tests, and then try out each of the test
methods. Are any assertion errors generated? If so, do you understand why?
Exercise 12.37 The changeDetails method of AddressBook currently has no assert
statements. One assertion we could make about it is that the address book should contain the
same number of entries at the end of the method as it did at the start. Add an assert statement
(and any other statements you might need) to check this. Run the testChange method of
AddressBookDemo after doing so. Do you think this method should also include the check
for a consistent size?
 
Search WWH ::




Custom Search