Handling Complexity - Encapsulation Print E-mail
Wednesday, 31 January 2001 09:24
Article Index
Handling Complexity
Data Abstraction
Modularization
Encapsulation
All Pages

Encapsulation: A Modular Data Abstraction

When combined, data abstraction and modularization together form the powerful concept of encapsulation: a module is used to implement a data abstraction. The module defines the structure and type of the data, and the methods that manipulate it. The methods serve as an interface to allow any outside program modules to access the actual data in the encapsulated module, so that the outside modules don’t have to worry about how to handle the specific kind of data. This lets the programmer focus on narrower problems and allows for simpler coding.

In the sorting example above, we have three separate modules: the main program code, the numeric-type data abstraction, and the string-type data abstraction. As you might have guessed, the two modular data abstractions would be implemented as objects in an OOPL, since they are self-contained units. What might not be so obvious is that some OOPLs, like Smalltalk and Java, would also implement the main solution algorithm as an object. As these languages see it, the solution has its own complete behavior and data.

Note that encapsulation is not unique to OOP. What is unique is that OOP uses objects to implement encapsulation, and its entire programming philosophy revolves around these modular data abstractions.

 

Information hiding: An important issue in encapsulation is whether or not an object should let other objects access its data. If an object let just anyone change its data, things could easily get out of hand. And sometimes an object would prefer to tell another object about itself only when asked, rather than letting just anyone snoop around inside. It’s not just a matter of being secretive, but if a programmer doesn’t keep strict control over which object accesses what, the program could easily get out of hand. Thus most OOPLs hide the information in their objects to some degree. Smalltalk, for example, doesn’t allow any outside objects to access data members. C++ and Java, on the other hand, let programmers specify which outside objects can access an object’s data, and how much they can access. (Cook 1990)


Now that we understand that an object is an encapsulation of data and methods, let’s explore their other property—behavior sharing—that defines OOP.



Last Updated on Tuesday, 28 October 2008 13:42