Encapsulation (computer science)
   HOME

TheInfoList



OR:

In software systems, encapsulation refers to the bundling of data with the mechanisms or methods that operate on the data, or the limiting of direct access to some data, such as an object's components. Encapsulation allows developers to present a consistent and usable interface which is independent of how a system is implemented internally. As one example, encapsulation can be used to hide the values or state of a structured data object inside a class, preventing direct access to them by clients in a way that could expose hidden implementation details or violate state invariance maintained by the methods. All
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
(OOP) systems support encapsulation, but encapsulation is not unique to OOP. Implementations of
abstract data types In computer science, an abstract data type (ADT) is a mathematical model for data types. An abstract data type is defined by its behavior (semantics) from the point of view of a '' user'', of the data, specifically in terms of possible values, ...
,
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 s ...
, and
libraries A library is a collection of Document, materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or electronic media, digital access (soft copies) materials, and may be a ...
, among other systems, also offer encapsulation. The similarity has been explained by programming language theorists in terms of existential types.


Meaning

In
object-oriented programming languages Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of p ...
, 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 ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
'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: *Scien ...
s (or other functions) operating on those 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 based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, while some programming languages that provide lexical closures view encapsulation as a feature of the language orthogonal 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, information hiding is the principle of segregation of the ''design decisions'' in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decisio ...
is defined as a separate notion by those who prefer the second definition. The features of encapsulation are supported using classes in most object-oriented languages, although other alternatives also exist.


Encapsulation and inheritance

The authors of '' Design Patterns'' discuss the tension between
inheritance Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Officia ...
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, 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 ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
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
robustness Robustness 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'' ca ...
, by allowing the developer to limit the interdependencies between software components. Some languages like Smalltalk and
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called ...
only allow access via object methods, but most others (e.g.,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, C#, Delphi 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 151.6 million people, Java is the world's mos ...
) 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 languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the enc ...
" 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
reflection Reflection or reflexion may refer to: Science and technology * Reflection (physics), a common wave phenomenon ** Specular reflection, reflection from a smooth surface *** Mirror image, a reflection in a mirror or in water ** Signal reflection, in ...
API (Ruby, Java, C#, etc.), sometimes by mechanism like
name mangling In compiler construction, name mangling (also called name decoration) is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages. It provides a way of e ...
(
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
), 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 secure computing systems, one of the existing security models. A capability (known in some systems as a key) is a communicable, unforgeable token of authority. It refers to a value that refer ...
(adhering to the object-capability model) are an exception, and guarantee strong encapsulation.


Examples


Restricting data fields

Languages like
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, 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 151.6 million people, Java is the world's mos ...
,
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
,
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT, ...
, and Delphi 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 151.6 million people, Java is the world's mos ...
: 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, an opaque data type is a data type whose concrete data structure is not defined in an interface. This enforces information hiding, since its values can only be manipulated by calling subroutines that have access to the missing ...
. 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: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
, 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, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new clas ...
*
Object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
*
Software design pattern In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine co ...
*
Facade pattern The facade pattern (also spelled ''façade'') is a software-design pattern commonly used in object-oriented programming. Analogous to a facade in architecture, a facade is an object that serves as a front-facing interface masking more complex und ...


References

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