3 | Encapsulation and Implementation Hiding
As you can see in Listing 3.9, the code inside class
1
cl_date is almost identical to
that of function module Z_DATE_SET_DAY from Listing 3.1. However, one major
difference between the two approaches is the fact that method set_day works on
an internal date data object (i.e., private attribute date) rather than an external
one provided via its method interface. By encapsulating this data element inside
the class, we have eliminated the need for maintaining a local Date data structure
within the calling program. Now. programs can simply work with object refer-
ences of type lcl.date without having to worry about keeping up with other
related data objects (i.e., structures containing the date value). This also simplifies
the interface for method set_day because we no longer need to pass in a refer-
ence to a Date data structure for the method to have data to work on.
With our new class-based Date library in tow, let's now revisit some of the main-
tenance scenarios described in Section 3.1.2, Case Study: A Procedural Code
Library. Here, if we are asked to enhance the icl_date class to support time-
stamps, we can either change the type of attribute date or add an additional
attribute to keep track of the time component of the timestamp. Obviously, this
changes the implementation of class lcl_date, but it does so without disturbing
the existing interface.
In other words, because we are no longer passing Date data structures back and
forth, method calls from client programs are not affected by this change. Instead,
the public interface for the class can simply expand to incorporate additional
methods that can be used to manipulate the time element of the date. We have
also addressed data corruption problems by encapsulating the data inside the
boundaries of the object. The use of the private visibility section ensures that
these boundaries are upheld. By removing the Date structure from the method
interface and encapsulating it internally as a private attribute, we have effectively
hidden this implementation concern from the user. Separating the interface of a
class from its implementation is a very effective design technique that helps you
develop classes that are much more responsive to change.
3.5 Designing by Contract
Encapsulation and implementation hiding techniques can be used to define very
precise public interfaces for a class. These interfaces help to form a contract
between the developer of
a
class and users of that class. The contract metaphor is
102