Encapsulation (computer programming): Difference between revisions

Content deleted Content added
m Attempted to make more clear. Minor edit.
RussBot (talk | contribs)
m Robot: Editing intentional link to disambiguation page in hatnote per WP:INTDABLINK (explanation)
 
(26 intermediate revisions by 18 users not shown)
Line 1:
{{Short description|Bundling of data}}
{{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" /> 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 (computer programming)|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.
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.
 
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" /> Encapsulation allows developers to present a consistent and usable interface whichthat is independent of howits ainternal system is implemented internallyimplementation. As one example, encapsulation can be used to hide the values or state of a structured data object inside a [[Class (computer programming)|class]],. preventingThis directprevents accessclients tofrom themdirectly byaccessing clientsthis information in a way that could expose hidden implementation details or violate [[State (computer science)|state]] invariance maintained by the methods.
All [[object-oriented programming]] (OOP) systems support encapsulation, but encapsulation is not unique to OOP. Implementations of [[abstract data types]], [[module (programming)|modules]], and [[library (computing)|libraries]], among other systems, 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>
 
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]].
 
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]], among other systems, 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>
 
== Meaning ==
Line 12 ⟶ 17:
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.
 
The second definition is motivated by the factreflects that in many object-oriented languages, and other related fields, the components are not hidden automatically and this can be overridden;. thusThus, [[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-->
 
The features of encapsulation are supported using [[class (computer programming)|class]]es in most object-oriented languages, although other alternatives also exist.
 
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>
 
=== Encapsulation and inheritance ===
Line 35 ⟶ 42:
== 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 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 (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 a degree ofsome 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.
Line 43 ⟶ 50:
=== 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:
Line 51 ⟶ 60:
public class Account
{
private decimal accountBalance_accountBalance = 500.00m;
 
public decimal CheckBalance()
{
return this.accountBalance_accountBalance;
}
}
Line 178 ⟶ 187:
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 |page=464 |edition= 2nd |urlpage=https://www.stormingrobots.com/prod/tutorial/pdf/kingBook-ch1to10.pdf |access-date=1 November 2019}}</ref><ref>King, Kim N. ''C programming: a modern approach''. WW Norton & Company, 2008. Ch. 18, p. 464, {{ISBN|0393979504}}</ref>
<syntaxhighlight lang="c">
// Header file "api.h"
Line 238 ⟶ 247:
* [[Object-oriented programming]]
* [[Software design pattern]]
* [[Facade pattern]]
 
== ReferencesCitations ==
{{Reflist}}
 
== References ==
*{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}}
 
[[Category:Object-oriented programming]]