Encapsulation (computer programming): Difference between revisions

Content deleted Content added
Simtay (talk | contribs)
No edit summary
Line 7:
 
== As information hiding mechanism ==
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++ or 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/> PleaseIt noteshould be noted that the ISO C++ standard refers to "<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.
 
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 benefit of encapsulation is that it can reduce system complexity, and thus increases robustness, by allowing the developer to limit the interdependencies between software components.
 
Almost always there is a way to override such protection - usually via reflection API (Ruby, Java, C# etc.), sometimes by mechanism like name mangling ([[Python (programming language)|Python]]), or special keyword like <code>friend</code> in C++. This access is often necessary for debuggers, serialization, unit testing, but not uncommonly in normal code when <code>private</code> was overeagerly applied. [http://www.davidarno.org/2010/07/22/why-the-private-keyword-is-the-modern-day-goto/]