Java Reference
In-Depth Information
So what, we can ask, are the semantics of the operations that we have defined in the interface?
A usual response to this question would refer to the internal representation of the object that
implements the interface. We would say that there are state variables in any object of a class
that implements the Batter interface that hold the number of at-bats and the various results of
those at-bats. But this explanation presupposes an implementation of the Batter object that
might not be the actual implementation. After all, the class could have been implemented with
an internal representation that calculated the number of at-bats from the sum of the various
results, or calculated the various averages on the fly. One of the reasons that we use object-ori-
ented techniques is to allow for such variation where the different implementation strategies
don't change the semantics of the interface. But that means that we have a notion of the se-
mantics of the interface that is separate from the implementation.
A far more accurate way to explain the semantics of the interface is to give the meanings of
the methods in terms of each other. The meaning of getAtBats() , on this approach, is that it
returns the value equivalent to the number of times the atBat() method has been called with
an argument other than walk or sacrifice . The methods that return the various statistics can
be explained with reference to each other or to the atBat() method. Such descriptions not
only allow you to give the semantics of a method without presupposing the implementation
of that method, but also help to make sure that you are designing your interfaces correctly. If
you can't describe the meaning of your interface without referring to methods of some other
interface, then you have two interfaces that are dependent on each other, and that dependency
should be reflected in some way. If you have to describe the semantics of the operations of an
interface by referring to something in the implementation of a class, then you have an inter-
face that depends on implementation details, and something is wrong with your design.
The side effect of explaining the semantics of a method in terms of the effect on other methods
within the interface is that it gives an immediate way to write some quick tests for any class
that attempts to implement that interface. For example, if we wanted to test implementations
of the Batter interface, we could write a simple class like:
package examples.test;
import org.junit.Test;
import examples.Batter
import examples.Batter.AtBatResults;
Search WWH ::

Custom Search