Java Reference
In-Depth Information
Using assertions
Internal consistency checks
When we design or implement a class, we often have an intuitive sense of things that should
be true at a given point in the execution, but rarely state them formally. For instance, we would
expect a ContactDetails object to always contain at least one non-blank field, or, when
the removeDetails method is called with a particular key, we would expect that key to be
no longer in use at the end of the method. Typically, these are conditions we wish to establish
while developing a class, before it is released. In one sense, the sort of testing we discussed in
Chapter 7 is an attempt to establish whether we have implemented an accurate representation
of what a class or method should do. Characteristic of that style of testing is that the tests are
external to the class being tested. If a class is changed, then we should take the time to run
regression tests in order to establish that it still works as it should; it is easy to forget to do that.
The practice of checking parameters, which we have introduced in this chapter, slightly shifts
the emphasis from wholly external checking to a combination of external and internal checking.
However, parameter checking is primarily intended to protect a server object from incorrect
usage by a client. That still leaves the question of whether we can include some internal checks
to ensure that the server object behaves as it should.
One way we could implement internal checking during development would be through the nor-
mal exception-throwing mechanism. In practice, we would have to use unchecked exceptions,
because we could not expect regular client classes to include exception handlers for what are
essentially internal server errors. We would then be faced with the issue of whether to remove
these internal checks once the development process has been completed, in order to avoid the
potentially high cost of runtime checks that are almost certainly bound to pass.
The assert statement
In order to deal with the need to perform efficient internal consistency checks, which can be
turned on in development code but off in released code, an assertion facility is available in
Java. The idea is similar to what we saw in Chapter 7 with JUnit testing, where we asserted the
results we expected from method calls and the JUnit framework tested whether or not those
assertions were confirmed.
The address-book-assert project is a development version of the address-book projects that
illustrates how assertions are used. Code 12.16 shows the removeDetails method, which now
contains two forms of the assert statement .
Code 12.16
Using assertions for
internal consistency
* Remove the entry with the given key from the address book.
* The key should be one that is currently in use.
* @param key One of the keys of the entry to be removed.
* @throws IllegalArgumentException If the key is null.
Search WWH ::

Custom Search