HOME

TheInfoList




In
object-oriented programming Object-oriented programming (OOP) is a programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mai ...
(OOP), encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components. Encapsulation is used to hide the values or state of a structured data object inside a
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differently f ...
, preventing direct access to them by clients in a way that could expose hidden implementation details or violate state invariance maintained by the methods. Publicly accessible methods are generally provided in the class to access or modify the state more abstractly. In practice sometimes methods (so-called "getters" and "setters") are provided to access the values indirectly, but, although not necessarily a violation of abstract encapsulation, they are often considered a sign-post of potentially poor
object-oriented programming Object-oriented programming (OOP) is a programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mai ...
(OOP) design practice (an
Anti-pattern An anti-pattern is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive. The term, coined in 1995 by computer programmer Andrew Koenig, was inspired by the book ''Design Patterns (book), Desi ...
). This mechanism is not unique to OOP. Implementations of
abstract data types In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algo ...
, e.g.,
modules Broadly speaking, modularity is the degree to which a system's components may be separated and recombined, often with the benefit of flexibility and variety in use. The concept of modularity is used primarily to reduce complexity by breaking a syst ...
, offer a similar form of encapsulation. The similarity has been explained by programming language theorists in terms of existential types.


Meaning

In
object-oriented programming languages Object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Entity, something that is tangible and within the grasp of the senses ** Object (abstract), an object which does not exist at any particula ...
, and other related fields, encapsulation refers to one of two related but distinct notions, and sometimes to the combination thereof: * A language mechanism for restricting direct access to some of the
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Entity, something that is tangible and within the grasp of the senses ** Object (abstract), an object which does not exist at any particular time or pl ...
's components. * A language construct that facilitates the bundling of data with the
method Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scient ...
s (or other functions) operating on that data. Some programming language researchers and academics use the first meaning alone or in combination with the second as a distinguishing feature of
object-oriented programming Object-oriented programming (OOP) is a programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mai ...
, while some programming languages that provide lexical closures view encapsulation as a feature of the language
orthogonal In mathematics, orthogonality is the generalization of the notion of perpendicularity to the linear algebra of bilinear forms. Two elements ''u'' and ''v'' of a vector space with bilinear form ''B'' are orthogonal when . Depending on the bili ...
to object orientation. The second definition is motivated by the fact that in many object-oriented languages, and other related fields, the components are not hidden automatically and this can be overridden; thus,
information hiding In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algor ...
is defined as a separate notion by those who prefer the second definition. The features of encapsulation are supported using
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differently f ...
es in most object-oriented languages, although other alternatives also exist.


Encapsulation and inheritance

The authors of ''
Design Patterns ''Design Patterns: Elements of Reusable Object-Oriented Software'' (1994) is a software engineering book describing software design pattern In software engineering, a software design pattern is a general, reusable solution to a commonly occurri ...
'' discuss the tension between
inheritance Inheritance is the practice of passing on private property Private property is a legal designation for the ownership of property by non-governmental legal entities. Private property is distinguishable from public property Public property i ...
and encapsulation at length and state that in their experience, designers overuse inheritance. They claim that inheritance often breaks encapsulation, given that inheritance exposes a subclass to the details of its parent's implementation. As described by the
yo-yo problem In software development, the yo-yo problem is an anti-pattern that occurs when a programmer has to read and understand a program whose Inheritance (object-oriented programming), inheritance graph is so long and complicated that the programmer has to ...
, overuse of inheritance and therefore encapsulation, can become too complicated and hard to debug.


Information hiding

Under the definition that encapsulation "can be used to hide data members and member functions", the internal representation of an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Entity, something that is tangible and within the grasp of the senses ** Object (abstract), an object which does not exist at any particular time or pl ...
is generally hidden from view outside of the object's definition. Typically, only the object's own methods can directly inspect or manipulate its fields. Hiding the internals of the object protects its integrity by preventing users from setting the internal data of the component into an invalid or inconsistent state. A supposed benefit of encapsulation is that it can reduce system complexity, and thus increase
robustnessRobustness is the property of being strong and healthy in constitution. When it is transposed into a system, it refers to the ability of tolerating perturbations that might affect the system’s functional body. In the same line ''robustness'' can be ...
, by allowing the developer to limit the interdependencies between software components. Some languages like
Smalltalk Smalltalk is an object-oriented programming, object-oriented, dynamically typed reflection (computer science), reflective programming language. Smalltalk was created as the language underpinning the "new world" of computing exemplified by "human ...

Smalltalk
and
Ruby A ruby is a pink to blood-red coloured gemstone A gemstone (also called a gem, fine gem, jewel, precious stone, or semi-precious stone) is a piece of mineral crystal which, in cut and polished form, is used to make jewellery, jewelry or othe ...
only allow access via object methods, but most others (e.g.,
C++ C++ () is a general-purpose programming language In computer software, a general-purpose programming language is a programming language dedicated to a general-purpose, designed to be used for writing software in a wide variety of application ...

C++
, C#,
Delphi Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of , the major who was consulted about important decisions throughout the ancient classical world. The oracle was interna ...
or
Java Java ( id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 147.7 million people, Java is the world's List of ...
) offer the programmer a degree of control over what is hidden, typically via keywords like public and private. ISO C++ standard refers to protected, private and public as "
access specifiers Access modifiers (or access specifiers) are keywords in object-oriented language Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: da ...
" and that they do not "hide any information". Information hiding is accomplished by furnishing a compiled version of the source code that is interfaced via a header file. Almost always, there is a way to override such protection – usually via
reflectionReflection or reflexion may refer to: Philosophy * Self-reflection Science * Reflection (physics), a common wave phenomenon ** Specular reflection, reflection from a smooth surface *** Mirror image, a reflection in a mirror or in water ** Signal r ...
API (Ruby, Java, C#, etc.), sometimes by mechanism like
name mangling In compiler In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler ...
(
Python Python may refer to: * Pythonidae The Pythonidae, commonly known as pythons, are a family of nonvenomous snakes found in Africa, Asia, and Australia. Among its members are some of the largest snakes in the world. Ten genera and 42 species ...
), or special keyword usage like friend in C++. Systems that provide object-level
capability-based security Capability-based security is a concept in the design of Computer security, secure computing systems, one of the existing Computer security model, security models. A capability (known in some systems as a key) is a communicable, unforgeable Access t ...
(adhering to the
object-capability model The object-capability model is a computer security model. A capability describes a transferable right to perform one (or more) operations on a given object. It can be obtained by the following combination: :* An unforgeable reference (in the sens ...
) are an exception, and guarantee strong encapsulation.


Examples


Restricting data fields

Languages like
C++ C++ () is a general-purpose programming language In computer software, a general-purpose programming language is a programming language dedicated to a general-purpose, designed to be used for writing software in a wide variety of application ...

C++
, C#,
Java Java ( id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 147.7 million people, Java is the world's List of ...
,
PHP PHP is a general-purpose scripting language A scripting language or script language is a programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various k ...

PHP
,
Swift The Society for Worldwide Interbank Financial Telecommunication (SWIFT), legally S.W.I.F.T. SCRL, is a Belgium, Belgian cooperative society that serves as an intermediary and executor of financial transactions between banks worldwide. It also ...
, and
Delphi Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of , the major who was consulted about important decisions throughout the ancient classical world. The oracle was interna ...
offer ways to restrict access to data fields. Below is an example in C# that shows how access to a data field can be restricted through the use of a private keyword: class Program Below is an example in
Java Java ( id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 147.7 million people, Java is the world's List of ...
: public class Employee Encapsulation is also possible in non-object-oriented languages. In C, for example, a structure can be declared in the public API via the header file for a set of functions that operate on an item of data containing data members that are not accessible to clients of the API with the extern keyword. // Header file "api.h" struct Entity; // Opaque structure with hidden members // API functions that operate on 'Entity' objects extern struct Entity * open_entity(int id); extern int process_entity(struct Entity *info); extern void close_entity(struct Entity *info); // extern keywords here are redundant, but don't hurt. // extern defines functions that can be called outside the current file, the default behavior even without the keyword Clients call the API functions to allocate, operate on, and deallocate objects of an
opaque data type In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algori ...
. The contents of this type are known and accessible only to the implementation of the API functions; clients cannot directly access its contents. The source code for these functions defines the actual contents of the structure: // Implementation file "api.c" #include "api.h" struct Entity ; // API function implementations struct Entity * open_entity(int id) int process_entity(struct Entity *info) void close_entity(struct Entity *info)


Name mangling

Below is an example of
Python Python may refer to: * Pythonidae The Pythonidae, commonly known as pythons, are a family of nonvenomous snakes found in Africa, Asia, and Australia. Among its members are some of the largest snakes in the world. Ten genera and 42 species ...
, which does not support variable access restrictions. However, the convention is that a variable whose name is prefixed by an underscore should be considered private. class Car: def __init__(self) -> None: self._maxspeed = 200 def drive(self) -> None: print(f"Maximum speed is .") redcar = Car() redcar.drive() # This will print 'Maximum speed is 200.' redcar._maxspeed = 10 redcar.drive() # This will print 'Maximum speed is 10.'


See also

*
Inheritance (object-oriented programming) In object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "Object (computer science), objects", which can contain data and code: data in the form of Field (computer science), fields (of ...
*
Object-oriented programming Object-oriented programming (OOP) is a programming paradigm Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. Some paradigms are concerned mai ...
*
Software design pattern In software engineering Software engineering is the systematic application of engineering Engineering is the use of scientific principles to design and build machines, structures, and other items, including bridges, tunnels, roads, vehic ...
* Facade pattern


References

{{Reflist Object-oriented programming Articles with example Java code