Representational Encapsulation

Data types do not tell the full story of the representation either. Although much of the discussion about object-oriented design is in the direction of structure and syntax—the mechanics of encapsulation—you can make a strong case that meaning is the most important aspect. The purpose of an object and its characteristics need to be at the forefront of your mind as you design and use them. Ideally, the object design guides you toward the correct usage, but mainstream programming languages currently have little provision to encode full semantic intent.

With respect to the usage of an object, all of this protects us from creating objects with inconsistent internal state and provides the object’s implementation avenues for enhancement that preserve compatibility. Using methods to control access to attribute implementations hides any complexities in managing the internal state. It also allows the internal representation to change without requiring changes on the part of the users of the interface, when done properly.

However, this same level of indirection interferes with the verification of our implementation. Only the rare and simple object requires nothing more than its specification to be thoroughly tested. Driving testing by coverage further ensures a need for deeper visibility.

Consider the example of an object that buffers I/O, similar to Java’s BufferedReader1 class. The class should not expose the internals of buffering because the typical user only wants to read a stream more efficiently. Noticing that BufferedReader only implements the Closeable and Readable interfaces further underscores that intent.

1. http://docs.oracle.com/javase/6/docs/api/java/io/BufferedReader.html

The implementer of a buffered I/O class cares tremendously about the internal behavior of the object. Reading characters into the buffer, the number of characters in the buffer, and how the system behaves when the buffer is drained or when full all support the correctness of the functionality. Tightly encapsulating the implementation leaves the object hard to test. The developer can relax the strictness of the encapsulation in order to make it more testable and document that the exposed entry points should not be used, but users of the class can—and likely will—ignore the warnings at some point in time. Various languages provide other mechanisms that can be used to access the internals of the class, as examined in Chapter 9, but most of these mechanisms amount to forcibly prying open the locked box.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.48.161