Java Reference
In-Depth Information
Did You Know?
The Perils of Poor Encapsulation
Many novices (as well as many professional programmers) do not fully appreci-
ate the concepts of abstraction and encapsulation. It is tempting to write classes
that directly expose their data for clients to use, since private fields introduce
some complexity and restrictions into a program. However, there have been some
famous examples where a lack of proper encapsulation and abstraction caused a
large problem.
One such example is the “Y2K” (year 2000) or “millennium bug” scare of late
1999. The issue arose because a large number of computer programs represented
years by using only two digits, such as 72 for 1972. They followed this conven-
tion largely to save memory, since many of them were older programs written in
a language called COBOL during a time when memory was more scarce. Once
the year became 2000, the programs would incorrectly think that the year was
1900, and this might cause them to fail.
Making matters worse was the fact that many of these programs contained their
own handwritten logic for representing dates, which sometimes appeared in many
places in the code. In order for the program to represent a year with more than
two digits, many places in the code needed to be changed. In total, over $300 bil-
lion was spent on repairing old programs and systems to correct the Y2K problem.
If the old programs had used an encapsulated Date class that included a field
representing the year, far less work would have been needed to fix the Y2K bug.
This Date class could have been updated once and all the client code would have
received the benefits.
Surprisingly, Java's class libraries also contain examples of poorly encapsu-
lated classes. In the java.awt package, for example, the Point and Dimension
classes have public fields. (A Dimension object stores width and height fields
to represent the size of an onscreen region.) Many client programs access the
fields directly when they use these objects. Java's developers regret this decision:
Several classes in the Java platform libraries violate the advice that public
classes should not expose fields directly. Prominent examples include the
Point and Dimension classes in the java.awt package. Rather than
examples to be emulated, these classes should be regarded as cautionary
tales. [. . .] The decision to expose the internals of the Dimension class
resulted in a serious performance problem that could not be solved without
affecting clients.
—Joshua Bloch, Effective Java
 
Search WWH ::




Custom Search