In the earliest programming languages, any part of a pro-gram could access any other part simply by executing an instruction such as “jump” or “goto.” Later, the concept of the subroutine helped impose some order by creating rela-tively self-contained routines that could be “called” from the main program. At the time the subroutine is called, it is provided with necessary data in the form of global variables or (preferably) parameters, which are variable references or values passed explicitly when the subroutine is called. When the subroutine finishes processing, it may return val-ues by changing global variables or changing the values of variables that were passed as parameters (see procedures and functions).
While an improvement over the totally unstructured program, the subroutine mechanism has several drawbacks. If it is maintained as part of the main program code, one programmer may change the subroutine while another pro-grammer is still expecting it to behave as previously defined. If not properly restricted, variables within the subroutine might be accessed directly from outside, leading to unpre-dictable results. To minimize these risks, languages such as C and Pascal allow variables to be defined so that they are “local”—that is, accessible only from code within the func-tion or procedure. This is a basic form of encapsulation.
The class mechanism in C++ and other object-oriented languages provides a more complete form of encapsulation (see object-oriented programming, class, and C++). A class generally includes both private data and procedures or methods (accessible only from within the class) and public methods that make up the interface. Code in the main pro-gram uses the class interface to create and manipulate new objects of that class.
Encapsulation thus both protects code from uncontrolled modification or access and hides information (details) that programmers who simply want to use functionality don’t need to know about. Thus, high-quality classes can be designed by experts and marketed to other developers who can take advantage of their functionality without having to “reinvent the wheel.”
No comments:
Post a Comment