Object-oriented Programming Concepts

Encapsulation

Object-Oriented Design

Senthil Nayagan
Senthil Nayagan Publication

--

Photo by Tima Miroshnichenko from Pexels.

What is encapsulation?

Encapsulation is one of the core concepts of object-oriented programming. It’s the process of wrapping (covering, packaging, or bundling) the related code and data together into a single component.

Having said that, encapsulation is all about packaging related stuff together so we can hide it from external elements. Therefore, encapsulation guarantees the integrity of the data. The features of encapsulation are supported by using “classes” in most object-oriented programming languages.

How does encapsulation help conceal data?

Encapsulation is also known as data hiding, as it enables us to hide the internal representation of an object 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, only allow access via object methods, but most others (e.g., C++, C#, or Java) offer the programmer a degree of control over what is hidden, typically via keywords like public and private.

Hiding the internals of the object protects its integrity by preventing users from setting the internal data into an invalid or inconsistent state.

Data Integrity: By preventing the user from directly modifying attributes and forcing the user to use defined functions in order to modify them, data integrity is thus ensured.

Encapsulation and data hiding

It’s important to note that it should not be misunderstood that encapsulation is all about data hiding only. Encapsulation and data hiding aren’t the same thing — they are separate but interdependent. Encapsulation is all about grouping, packaging, or bundling related data and behaviour (methods) together.

Encapsulation is a programming language feature, and data hiding is a design principle.

Benefits of encapsulation

  • Grouping related data and behaviours together: The primary benefit of encapsulation is better maintainability as we are grouping related data and its behaviours (methods).
  • Controlled Access: Encapsulation allows us to control who can access what by means of access modifiers.
  • Data Integrity: Ensures data integrity by preventing users (by means of data hiding) from setting the internal data into an invalid or inconsistent state.

--

--

Senthil Nayagan
Senthil Nayagan Publication

I am a Data Engineer by profession, a Rustacean by interest, and an avid Content Creator.