Encapsulation
In computer programming, encapsulation is in its broadest sense the process of bringing together elements to produce a new entity. In this sense a function is itself a manifestation of encapsulation because it is a self-contained block of code that performs a set of actions and returns a value of a known type: a function "encapsulates" the combined functionality of the code within it to build new functionality. Similarly, user-defined data types like C structures, C++ and Java classes, and Perl "hashes" are examples of encapsulation because they encapsulate the data in them.
Indeed, object-oriented languages like C++ and Java profoundly depend upon encapsulation to create classes and objects as instances of those classes. Both of these languages contain keywords like "private" and "protected" that force the compiler to rigidly enforce the encapsulation of both data and functionality; encapsulating data in this way is called "data hiding."
Data hiding is where the details of an object or function are invisible to the outside world. The data can be accessed via functions that are privileged to see them, the "accessor functions," but they are not immediately visible in themselves. As an example, a class that represents a clock might reasonably contain data that represents the current time. It might be declared like this:
- class Clock {
- public:
- int getTime() const { return _theTime; }
- private:
- int _theTime;
- };
In the above class, anyone can ask an instance of a clock object for the time by calling the function getTime() like this:
- Clock myClock;
- int now = myClock.getTime();
But no one can get direct access to the member variable _theTime. The advantage of this is that one day the programmer who wrote the Clock class might wish to change the way it stores the time: he might want to make _theTime a character string, or measure it in camel's heartbeats. Without data hiding anyone who used _theTime direct and expected it to be an int would find his code suddenly breaking.
Using data hiding, as long as the interface to the data remains the same—that is, the programmer leaves the function declaration for getTime() alone (even though the implementation inside it can change)--no one will be any the wiser. This process of specifying functionality in terms of the interface rather than the implementation is called "abstraction." In the above class, the user of the class does not need to know about character strings or camels: all he needs to know is that if he calls getTime(), the class will return an int value.
Abstraction encourages programmers to think in terms of behavior rather than implementation; encapsulation enforces abstraction. And together these lead to better, more soundly structured, and, most important, more reliable programs.
This is the complete article, containing 441 words
(approx. 1 page at 300 words per page).