Home > Articles

  • Print
  • + Share This

Encapsulation

What should be apparent from Figure 3.1 is that we have bundled everything about the class into a nice, neat package. We formally define everything that the outside world needs to know about this class in terms of these properties and methods. We call the public properties and methods of a class its interface, which represents the concept of encapsulation. In the real-world account example, a customer does not necessarily need to know how the current balance is calculated based on transactions that are added, modified, or deleted. They just need to know their current balance. Similarly, users of the account class do not need to know how the class calculates the current balance either—just that the class properly handles it when the transaction processing methods are called. Thus, we can say that encapsulation has the effect of information hiding and the definition of narrow interfaces into the class. This concept is critical to the development of robust, maintainable applications.

A class might implement internal methods and properties but choose not to expose them to the outside world through its interface. Because of this, we are free to change the internal workings of these private items without affecting how the outside world uses our class through its public interface. Figure 3.2 shows how a public method calls a private method to perform a calculation that updates the value of a public property.

Figure 3.2 The interactions between public and private methods and properties.

Suppose, for the sake of argument, we were to expose the internal function (also known as a private method) that calculates current balances. We would do this by defining it to be public versus private. An application using this class, for whatever reason, might deem it acceptable to call this internal method directly and does so in a multitude of places. Now suppose that we must change the calling convention of this method by adding a new parameter to the parameter list, such that we have to modify every piece of software that references this internal method. Assume also that the public transaction methods would not have had to change, only the formerly private method. We have effectively forced ourselves into a potentially large code rewrite, debug, test, and deployment cycle that we could have otherwise handled simply within the object's private methods while leaving the public interface intact. We will see, in the COM model discussion to follow, that we can easily modify only the class and redeploy it across the user base with a minimum of effort. In the corporate world, this translates into time and money.

Because the term interface might be a difficult concept to grasp at first, it might be easier to think of as an electrical socket. In the 220-volt parts of the world, there are three-pronged sockets with one of the prongs oriented 90 degrees out from the other two. In the 110-volt parts of the world, there are two- and three-pronged plugs with a different geometry such that you cannot plug a 110-volt oriented plug into a 220-volt socket and vice-versa. Imagine if the 110-volt world suddenly began using 220-volt–style plugs and sockets (assuming voltage will not change). We would have to replace the plug on every electrical device along with all the wall sockets. It would be a huge mess. The same goes for properties and methods. After we define the interfaces of a class and write applications against them, making changes becomes difficult and costly.

TIP

When defining a class, assume every method is to be defined as private in scope (that is, hidden) unless there is good reason to make it public. When making a method public, take steps to ensure the stability of the calling convention (that is, the parameter list) over the life of the application. Use optional parameters as necessary to cover anticipated future needs.

Encapsulation also has the effect of protecting the integrity of objects, which are instantiated using the class definition. We have already touched on this when we stated that a class is responsible for its own inner workings. Outsiders cannot meddle in its internal affairs. Similarly, property definitions can be implemented such that the class rejects invalid property states during the setting process. For example, a date-based property could reject a date literal, such as "June 31, 1997," because it does not constitute a date on any calendar. Again, because the validation logic is contained within the class definition itself, modifying it to meet changing business needs occurs in a single place rather than throughout the application base. This aspect of encapsulation is important, especially for enterprise applications, when we discuss the implementation of validation logic in Chapter 9, "A Two-Part, Distributed Business Object." It further adds to our ability to develop robust, maintainable, and extensible applications.

NOTE

One of the common comments that newcomers to object-oriented development make is that it seems like unnecessary effort to package data and functionality together into a unit called a class. It also seems like extra work to define properties and methods, deciding what is to be public and what is to be private. It is much easier to just take a seat behind the keyboard and begin banging out some code. Although it is true that object-oriented development requires a different mindset and a somewhat formal approach to analysis and design, it is this formalization process that leads to less complex development over the long term. The old saying "penny-wise and dollar-foolish" applies here because some time saved up front will lead to potentially huge problems further into the development, and worse yet, the application launch process.

Let us switch gears by defining a class with some complexity—with a financial bond—so we can illustrate some other points and begin setting the stage for other features of object-orientation. Let us call it CBond (for Class Bond). We define several properties in tabular form in Table 3.1, methods in Table 3.2, and we provide a graphical depiction in Figure 3.3.

Table 3.1 Properties of a CBond Class

Property

Data Type

Description

Name

String

The descriptive name of the bond.

FaceValue

Single (Currency)

The final redemption value of the bond.

PurchasePrice

Single (Currency)

The price to purchase the bond.

CouponRate

Single (Percent)

The yearly bond coupon payment as a percentage of its face value.

BondTerm

Integer

The length of time to maturity for the bond, expressed in years, in the primary market.

BondType

Integer: (Enumeration[CouponBond, DiscountBond, ConsolBond])

The bond type used to drive calculation algorithms.


Table 3.2 Methods of a CBond Class

Method

Description

YieldToMaturity

Calculates the interest rate that equates the present value of the coupon payments over the life of the bond to its value today. Used in the secondary bond market.

BondPrice

Calculates the bond price as the sum of the present values of all the payments for the bond.

CurrentYield

Calculates the current yield as an approximation of the yield to maturity using a simplified formula. Note: Available only on CouponBond types.

DiscountYield

Calculates the discount yield based on the percentage gain on the face value of a bond and the remaining days to maturity.


Each method uses one or more of the public property values to perform the calculation. Some methods require additional information in the form of its parameter list, as can be seen in Figure 3.3. As you might guess, the BondType property helps each method determine how to perform the calculation. A sample Visual Basic implementation of the BondPrice method might be as follows in Listing 3.1.

Figure 3.3 UML representation of a CBond class.

Listing 3.1 The BondPrice Method

Public Function BondPrice(IntRate as Single) as Single
 Dim CouponPayment as Single
 Dim j as integer
 Dim p as single
 CouponPayment = CouponRate * FaceValue
 Select Case BondType
 Case btCouponBond
  For j = 1 to BondTerm
  p = p + CouponPayment/(1 + IntRate)^j   
  Next j
  p = p + FinalValue/(1 + IntRate)^BondTerm
  BondPrice = p
 Case btDiscountBond
  BondPrice = FaceValue/(1 + IntRate)
 Case btConsolBond
  BondPrice = CouponPayment/IntRate
 End Select
End Sub

As you can see, each value of the BondType property requires a different use of the properties to perform the correct calculation. The application using the class is not concerned with how the method performs the calculation, but only with the result. Now suppose that you need to modify the calculation algorithm for the BondPrice method. Because of encapsulation, you only need to modify the contents of the BondPrice method and nothing more. Better yet, because you have not changed the calling convention, the applications using the CBond class are none the wiser that a change occurred.

 

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.