Encapsulation (computer programming): Difference between revisions

Content deleted Content added
RussBot (talk | contribs)
m Robot: Editing intentional link to disambiguation page in hatnote per WP:INTDABLINK (explanation)
 
(99 intermediate revisions by 71 users not shown)
Line 1:
{{Short description|Bundling of data}}
In [[programming languages|object oriented programming languages,]] <!-- [[object-oriented programming language]]--> <!-- and related fields, like [[OODMBS]],--> '''encapsulation''' is used to refer to one of two related but distinct notions, and sometimes to the combination<ref>{{cite book |first=Michael Lee |last=Scott |title=Programming language pragmatics |edition=2 |publisher=Morgan Kaufmann |year=2006 |isbn=0-12-633951-1 |page=481 |quote=Encapsulation mechanisms enable the programmer to group data and the subroutines that operate on them together in one place, and to hide irrelevant details from the users of an abstraction.}}</ref><ref name=Dale>{{cite book |first=Nell B. |last=Dale |first2=Chip |last2=Weems |title=Programming and problem solving with Java |edition=2nd |publisher=Jones & Bartlett |year=2007 |isbn=0-7637-3402-0 |page=396}}</ref> thereof:
{{Other uses|Encapsulation (disambiguation){{!}}Encapsulation}}
In software systems, '''encapsulation''' refers to the bundling of data with the mechanisms or methods that operate on the data. It may also refer to the limiting of direct access to some of that data, such as an object's components.<ref name="Rogers01" /> Essentially, encapsulation prevents external code from being concerned with the internal workings of an object.
 
Encapsulation allows developers to present a consistent interface that is independent of its internal implementation. As one example, encapsulation can be used to hide the values or state of a structured data object inside a [[Class (computer programming)|class]]. This prevents clients from directly accessing this information in a way that could expose hidden implementation details or violate [[State (computer science)|state]] invariance maintained by the methods.
* A language mechanism for restricting direct access to some of the [[object (computer science)|object]]'s components.<ref>{{cite book |authorlink=John C. Mitchell |first=John C. |last=Mitchell |title=Concepts in programming languages |publisher=Cambridge University Press |year=2003 |isbn=0-521-78098-5 |page=522}}</ref><ref name=Pierce>{{cite book |last=Pierce |first=Benjamin |authorlink=Benjamin C. Pierce |title=[[Types and Programming Languages]] |publisher=MIT Press |year=2002 |isbn=0-262-16209-1 |page=266 |ref=harv}}</ref>
* A language construct that facilitates the bundling of data with the [[Method (computer programming)|method]]s <!-- I object to the word method being used here because in lisp languages programmers cannot distinguish methods from normal functions at the call site. Behavior equivalent to methods may be implemented as normal functions. encapsulation is not dependent on implementation but on behavior--> (or other functions) operating on that data.<ref name=Rogers01>{{cite web |first=Wm. Paul |last=Rogers |url=http://www.javaworld.com/javaworld/jw-05-2001/jw-0518-encapsulation.html?page=9 |title=Encapsulation is not information hiding |publisher=JavaWorld |date=18 May 2001}}</ref><ref>{{cite book |first=Thomas M. |last=Connolly |first2=Carolyn E. |last2=Begg |title=Database systems: a practical approach to design, implementation, and management |edition= 4th |publisher=Pearson Education |year=2005 |isbn=0-321-21025-5 |chapter=Ch. 25: Introduction to Object DMBS § Object-oriented concepts |page=814}}</ref>
 
Encapsulation also encourages programmers to put all the code that is concerned with a certain set of data in the same class, which organizes it for easy comprehension by other programmers. Encapsulation is a technique that encourages [[Coupling (computer programming)|decoupling]].
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]], while some programming languages that provide [[Closure (computer programming)|lexical closures]] view encapsulation as a feature of the language [[orthogonal#Computer science|orthogonal]] to object orientation.
 
All [[object-oriented programming]] (OOP) systems support encapsulation,<ref>{{Cite web |title=What is Object-Oriented Programming (OOP)? |url=https://www.techtarget.com/searchapparchitecture/definition/object-oriented-programming-OOP |access-date=2024-03-02 |website=App Architecture |language=en}}</ref><ref>{{Cite web |title=Encapsulation in Object Oriented Programming (OOPS) |url=https://www.enjoyalgorithms.com/blog/encapsulation-in-oops/ |access-date=2024-03-02 |website=www.enjoyalgorithms.com}}</ref> but encapsulation is not unique to OOP. Implementations of [[abstract data types]], [[module (programming)|modules]], and [[library (computing)|libraries]] also offer encapsulation. The similarity has been explained by programming language theorists in terms of [[existential types]].<ref>{{harvnb|Pierce|2002|loc=§ 24.2 Data Abstraction with Existentials}}</ref>
The second definition is motivated by the fact that in many of the OOP languages hiding of components is not automatic or can be overridden; thus, [[information hiding]] is defined as a separate notion by those who prefer the second definition.<!-- this is based on all the refs given above, so no inline cite here-->
 
== Meaning ==
The features of encapsulation are supported using classes in most object-oriented programming languages, although other alternatives also exist.
In [[object-oriented programming languages]], and other related fields, <!-- [[object-oriented programming language]]--> <!-- and related fields, like [[OODMBS]],--> encapsulation refers to one of two related but distinct notions, and sometimes to the combination thereof:<ref>{{cite book |first=Michael Lee |last=Scott |title=Programming language pragmatics |edition= 2 |publisher=Morgan Kaufmann |year=2006 |isbn=978-0-12-633951-2 |page=481 |quote=Encapsulation mechanisms enable the programmer to group data and the subroutines that operate on them together in one place, and to hide irrelevant details from the users of an abstraction}}</ref><ref name="Dale">{{cite book |first1=Nell B. |last1=Dale |first2=Chip |last2=Weems |title=Programming and problem solving with Java |edition= 2nd |publisher=Jones & Bartlett |year=2007 |isbn=978-0-7637-3402-2 |page=396}}</ref>
 
* A language mechanism for restricting direct access to some of the [[object (computer science)|object]]'s components.<ref>{{cite book |author-link=John C. Mitchell |first=John C. |last=Mitchell |title=Concepts in programming languages |publisher=Cambridge University Press |year=2003 |isbn=978-0-521-78098-8 |page=522}}</ref><ref name=Pierce>{{cite book |last=Pierce |first=Benjamin |author-link=Benjamin C. Pierce |title=Types and Programming Languages |publisher=MIT Press |year=2002 |isbn=978-0-262-16209-8 |page=266 |title-link=Types and Programming Languages }}</ref>
== General definition ==
* A language construct that facilitates the bundling of data with the [[method (computer programming)|method]]s <!-- I object to the word method being used here because in lisp languages programmers cannot distinguish methods from normal functions at the [[call site]]. Behavior equivalent to methods may be implemented as normal functions. encapsulation is not dependent on implementation but on behavior--> (or other functions) operating on those data.<ref name=Rogers01>{{cite web |last1=Rogers |first1=Wm. Paul |date=2001-05-18 |df=dmy |url=https://www.infoworld.com/article/2075271/encapsulation-is-not-information-hiding.html |title=Encapsulation is not information hiding |work=[[JavaWorld]] |access-date=2020-07-20}}</ref><ref>{{cite book |first1=Thomas M. |last1=Connolly |first2=Carolyn E. |last2=Begg |title=Database systems: a practical approach to design, implementation, and management |edition= 4th |publisher=Pearson Education |year=2005 |isbn=978-0-321-21025-8 |chapter=Ch. 25: Introduction to Object DMBS § Object-oriented concepts |page=814}}</ref>
 
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]], while some programming languages that provide [[closure (computer programming)|lexical closures]] view encapsulation as a feature of the language [[orthogonality#Computer science|orthogonal]] to object orientation.
Encapsulation ''of the fundamentals'' of OOP ([[object-oriented programming]]). It refers to the bundling of data with the methods that operate on that data.<ref name=Rogers01/> Encapsulation is ''used to hide the values or state of a structured data object inside a class'', preventing unauthorized parties' direct access to them. Publicly accessible methods are generally provided in the class (so-called ''getters'' and ''setters'') to access the values, and other client classes call these methods to retrieve and modify the values within the object.
 
The second definition reflects that in many object-oriented languages, and other related fields, the components are not hidden automatically and this can be overridden. Thus, [[information hiding]] is defined as a separate notion by those who prefer the second definition.<!-- this is based on all the refs given above, so no inline cite here-->
This mechanism is not unique to object-oriented programming. Implementations of [[abstract data types]], e.g. [[module (programming)|modules]], offer a similar form of encapsulation. This similarity stems from the fact that both notions rely on the same mathematical fundamental of an [[existential type]].<ref>{{harvnb|Pierce|2002|loc=§ 24.2 Data Abstraction with Existentials}}</ref>
 
The features of encapsulation are supported using [[class (computer programming)|class]]es in most object-oriented languages, although other alternatives also exist.
== An information-hiding mechanism ==
{{See also|Information hiding}}
{{em| Encapsulation can be used to hide data members and members function.}} Under this definition, encapsulation means that the internal representation of an [[object (computer science)|object]] 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. Some languages like [[Smalltalk]] and [[Ruby (programming language)|Ruby]] only allow access via object methods, but most others (e.g. [[C++]], [[C Sharp (programming language)|C#]], [[Delphi (programming language)|Delphi]] or [[Java (programming language)|Java]]) offer the programmer a degree of control over what is hidden, typically via keywords like <code>public</code> and <code>private</code>.<ref name=Pierce/> ISO C++ standard refers to <code>protected</code>, <code>private</code> and <code>public</code> as "[[access specifiers]]" 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.
 
Encapsulation may also refer to containing a repetitive or complex process in a single unit to be invoked. Object-oriented programming facilitate this at both the method and class levels. This definition is also applicable to [[procedural programming]].<ref>{{Cite book |last=McDonough |first=James E. |title=Object-Oriented Design with ABAP: A Practical Approach |publisher=[[Apress]] |year=2017 |isbn=978-1-4842-2837-1 |___location= |chapter=Encapsulation |doi=10.1007/978-1-4842-2838-8 |via=[[O'Reilly Media|O'Reilly]]}}</ref>
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 (computer science)|robustness]], by allowing the developer to limit the inter-dependencies between software components{{Citation needed|date=April 2014}}.
 
=== Encapsulation and inheritance ===
Almost always, there is a way to override such protection &ndash; usually via [[Reflection (computer programming)|reflection]] API (Ruby, Java, C#, etc.), sometimes by mechanism like [[name mangling]] ([[Python (programming language)|Python]]), or special keyword usage like <code>friend</code> in C++.
The authors of ''[[Design Patterns]]'' discuss the tension between [[inheritance (object-oriented programming)|inheritance]] 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.<ref name="GoF">{{cite book
| last1 = Gamma
| first1 = Erich
| last2 = Helm
| first2 = Richard
| last3 = Johnson
| first3 = Ralph
| last4 = Vlissides
| first4 = John
| title = Design Patterns
| date = 1994
| publisher = Addison-Wesley
| isbn = 978-0-201-63361-0| url-access = registration
| url = https://archive.org/details/designpatternsel00gamm
}}</ref> As described by the [[yo-yo problem]], overuse of inheritance and therefore encapsulation, can become too complicated and hard to debug.
 
== Information hiding ==
{{Main|Information hiding}}
Under the definition that encapsulation "can be used to hide data members and member functions", the internal representation of an [[object (computer science)|object]] is generally hidden 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 (computer science)|robustness]], by allowing the developer to limit the interdependencies between software components.{{Citation needed|date=April 2014}}
 
Some languages like [[Smalltalk]] and [[Ruby (programming language)|Ruby]] only allow access via object methods, but most others (e.g., [[C++]], [[C Sharp (programming language)|C#]], [[Delphi (programming language)|Delphi]] or [[Java (programming language)|Java]]{{sfn|Bloch|2018|loc=Chapter §4 Item 15 Minimize the accessibility of classes and members|pp=73-77}}) offer the programmer some control over what is hidden, typically via keywords like <code>public</code> and <code>private</code>.<ref name=Pierce/> ISO C++ standard refers to <code>protected</code>, <code>private</code> and <code>public</code> as "[[access specifiers]]" 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 &ndash; usually via [[Reflection (computer programming)|reflection]] API (Ruby, Java, C#, etc.), sometimes by mechanism like [[name mangling]] ([[Python (programming language)|Python]]), or special keyword usage like <code>friend</code> in C++. Systems that provide object-level [[capability-based security]] (adhering to the [[object-capability model]]) are an exception, and guarantee strong encapsulation.
 
=== Examples ===
==== Restricting data fields ====
Languages like [[C++]], [[C Sharp (programming language)|C#]], [[Java (programming language)|Java]],{{sfn|Bloch|2018|loc=Chapter §4 Item 15 Minimize the accessibility of classes and members|pp=73-77}} [[PHP]], [[Swift (programming language)|Swift]], and [[Delphi (programming language)|Delphi]] offer ways to restrict access to data fields.
 
[[File:UML encapsulation.svg]]
 
Below is an example in [[C Sharp (programming language)|C#]] that shows how access to a data field can be restricted through the use of a <code>private</code> keyword:
<sourcesyntaxhighlight lang="csharp">
class Program
{
public class Account {
{
private decimal accountBalance = 500.00m;
private decimal _accountBalance = 500.00m;
 
public decimal CheckBalance() {
{
return accountBalance;
return _accountBalance;
}
}
}
}
 
static void Main() {
{
Account myAccount = new Account();
decimal myBalance = myAccount.CheckBalance();
 
/* This Main method can check the balance via the public
* "CheckBalance" method provided by the "Account" class
* but it cannot manipulate the value of "accountBalance" */
}
}
}
</syntaxhighlight>
</source>
 
Below is an example in [[Java (programming language)|Java]]:
<sourcesyntaxhighlight lang="java">
 
public class Employee {
Line 53 ⟶ 87:
public BigDecimal getSalary() {
return this.salary;
}
 
Line 61 ⟶ 95:
}
}
</syntaxhighlight>
</source>
 
<!--Below is an example in [[PHP]]:
 
<sourcesyntaxhighlight lang="php">
class Account
{
/**
* How much money is currently in the account
Line 76 ⟶ 111:
* @param float $currentAccountBalance Initialize account to this dollar amount
*/
public function __construct($currentAccountBalance) {
{
$this->accountBalance = $currentAccountBalance;
}
Line 85 ⟶ 121:
* @return void
*/
public function deposit($money): {null
{
$this->accountBalance += $money;
}
Line 95 ⟶ 132:
* @return void
*/
public function withdraw($money): {null
{
if ($this->accountBalance < $money) {
throw new Exception('Cannot withdraw $' . $money . ' from account as it contains $' . $this->accountBalance);
Line 125 ⟶ 163:
// Our code forbids us from withdrawing more than we have
$myAccount->withdraw(600.00); // Exception Message: Cannot withdraw $600 from account as it contains $505.79
</syntaxhighlight>
</source>
 
Below is an example in [[Swift (programming language)|Swift]]. The <code>balance</code> property cannot be accessed directly; a merchant can only check whether the requested amount is available for spending using the <code>isAvailable(_:)</code> method.
Encapsulation is also possible in non-object-oriented languages. In C, for example, a structure can be declared in the public API (i.e., 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:
 
<source lang="csharp">
<syntaxhighlight lang="swift">
struct CreditCard {
   
    private var balance: Double
   
    init(withBalance balance: Double) {
        self.balance = balance
    }
   
    func isAvailable(_ amount: Double) -> Bool {
        return balance >= amount
    }
   
}
 
var myCard = CreditCard(withBalance: 100)
myCard.balance // Error: 'balance' is inaccessible due to 'private' protection level
myCard.isAvailable(100) // true
myCard.isAvailable(101) // false
</syntaxhighlight>-->
Encapsulation is also possible in non-object-oriented languages. In [[C (programming language)|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 <code>extern</code> keyword.<ref>{{cite book |last1=King |first1=K. N. |url= |title=C Programming: A Modern Approach |date=2008 |publisher=W. W. Norton & Company |isbn=978-0393979503 |edition=2nd |page=464}}</ref>
<syntaxhighlight lang="c">
// Header file "api.h"
 
Line 137 ⟶ 197:
extern int process_entity(struct Entity *info);
extern void close_entity(struct Entity *info);
// extern keywords here are redundant, but they wondon't hurt.
// extern keyword defines functions to have external linkage (i.e.that can be called outside the current file), the default behavior even without the keyword
</syntaxhighlight>
// which is the default behavior even without the keyword extern
</source>
Note on extern keyword from K.N. King.<ref>King, Kim N. C programming: a modern approach. WW Norton & Company, 2008. Ch. 18, p. 464, {{ISBN|0393979504}}</ref>
 
Clients call the API functions to allocate, operate on, and deallocate objects of an [[opaque data type]]. 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:
<sourcesyntaxhighlight lang="csharpc">
// Implementation file "api.c"
 
#include "api.h"
 
// Complete definition of the 'Entity' object
struct Entity {
int ent_id; // ID number
Line 165 ⟶ 222:
void close_entity(struct Entity *info)
{ ... }
</syntaxhighlight>
</source>
 
==== Name mangling ====
== Encapsulation and Inheritance ==
{{main|Name mangling}}
The authors of Design Patterns<ref name="GoF">
Below is an example of [[Python (programming language)|Python]], 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.<ref>{{cite web |last1=Bader |first1=Dan |title=The Meaning of Underscores in Python |url=https://dbader.org/blog/meaning-of-underscores-in-python |website=Improve Your Python Skills |access-date=1 November 2019}}</ref>
{{cite book
| last1 = Gamma
| first1 = Erich
| last2 = Helm
| first2 = Richard
| last3 = Johnson
| first3 = Ralph
| last4 = Vlissides
| first4 = John
| title = Design Patterns
| date = 1994
| publisher = Addison-Wesley
| isbn = 0-201-63361-2
}}</ref> discuss the tension between inheritance and encapsulation at length and state that in their experience, designers overuse inheritance. The danger is stated as follows:
 
<syntaxhighlight lang="python">
{{quote |text=Because inheritance exposes a subclass to details of its parent's implementation, it's often said that "inheritance breaks encapsulation" |author=Gang of Four |source=Design Patterns<ref name="GoF" /> (Chapter 1)}}
class Car:
def __init__(self) -> None:
self._maxspeed = 200
def drive(self) -> None:
print(f"Maximum speed is {self._maxspeed}.")
redcar = Car()
redcar.drive() # This will print 'Maximum speed is 200.'
 
redcar._maxspeed = 10
redcar.drive() # This will print 'Maximum speed is 10.'
</syntaxhighlight>
 
== See also ==
* [[Inheritance (object-oriented programming)]]
* [[Object-oriented programming]]
* [[Software design pattern]]
* [[Facade pattern]]
 
== Citations ==
{{Reflist}}
 
== References ==
*{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}}
{{Reflist|2}}
 
==External links==
* {{Citation/make link|http://www.soapatterns.org/service_encapsulation.php|SOA Patterns.org}}
* {{Citation/make link|http://telecomacadmey.com/understanding-encapsulation-troubleshooting-network/|Encapsulation}}
 
[[Category:Object-oriented programming]]
[[Category:Articles with example Java code]]
[[Category:Programming principles]]