There are four pillars in Object-Oriented Programming (OOP), one of which is ‘encapsulation’, which refers to the good practice of hiding the inner works of an object and its implementation details, where access is only possible through public methods. As one of the pillars of OOP, it is beneficial to me as a learning programmer to understand about the purpose of ‘encapsulation’ and how it can be effectively applied.
I realized during one of my classes — when we were reviewing these four pillars — that while I knew the principle by name, I had never learned encapsulation in detail nor how to best implement it into my code. Looking back at code I had written in the past, it was clear that I did not always follow this practice (i.e. using dangerous global variables as attributes in my objects).
The blog “The four pillars of object-oriented programming — part 1 — encapsulation”, written by Bas Dijkstra, helped better illustrate for me what encapsulation is supposed to do.
Firstly, encapsulation is all about making attributes private. By doing so, an object’s attribute is protected from being accidentally — or maliciously — altered. Instead of accessing the attribute directly, the value can and should be returned through a public method within the object, essentially making the attribute ‘read-only’.
By doing this, a programmer gains more security and control over the code, reducing the amount of unwanted behavior in the system as a whole.
Secondly, good encapsulation is the product of good design. In another blog, “Encapsulation in Functional Programming”, by Mark Seemann, which I found by looking deeper into the strategies of implementing encapsulation into code, talks about creating a ‘contract’ for each class. The contract outline three properties of a class:
- Preconditions — what are the minimal requirements for the object to function?
- Invariants — which attributes of the object do not/cannot change?
- Post-conditions — what are the boundaries/rules of the object after it is created?
Though the article focuses more heavily on encapsulation for functional programming, the design strategy also benefits OOP. Having these properties outlined in the contract of a class helps the programmer understand not only what needs to be encapsulated, but also how it can be encapsulated.
In addition, because of the nature of encapsulation and the amount of control it provides a programmer over the code, testing for such classes that follow the principle becomes much simpler and easier to do .
While a simple principle, encapsulation is a powerful and practical strategy that makes code secure and easy to manage by hiding the inner works of a class behind public methods.
Sources:
- Encapsulation in Functional Programming
- The four pillars of object-oriented programming – part 1 – encapsulation
From the blog Stories by Namson Nguyen on Medium by Namson Nguyen and used with permission of the author. All other rights reserved by the author.
