What Is Encapsulation?
Over the next few weeks, I want to explain the four fundamental concepts of Object-Oriented Programming (OOP) – Encapsulation, Abstraction, Inheritance and Polymorphism. Today we’ll explore Encapsulation.
What is Encapsulation? Let’s write the word differently: En-capsul-ation. Hmm, something to do with a capsule. My first web search result for ‘capsule’ returned:
“a small case or container, especially a round or cylindrical one.”
Right. People put things into capsules; something they want to protect. Capsules have an interior and an exterior.
This meaning of an interior and an exterior carries over into OOP. Encapsulation refers to the idea of information hiding. It’s the concept that callers of a class don’t have to have access to its internal data and behaviour. Callers shouldn’t care HOW the class does its work. Callers should only care WHAT the class does while trusting that it does its delegated job correctly and well.
In this way, Encapsulation is an allocation of responsibility to a particular class.
Say, we had an instance of an Invoice class, as shown in the code below and we call the Total property on this instance:
var invoice = new Invoice(); // Add invoice lines to invoice. var total = invoice.Total;
Should we be concerned about the encapsulated algorithm underlying Total? No, not really. Not with the work we are currently doing. We are trusting that the algorithm, whatever it is inside of class Invoice, is correct and working as expected. If it isn’t, then that is the problem of the Invoice class, not of the code consuming invoice.Total. If there is a problem, it needs to be fixed in Invoice.
In this manner, we achieve the division of labour or separation of concerns in programming parlance.
And that’s all there is to Encapsulation. It’s not a difficult concept. It is fundamental to OOP.
So please remember that in Object-Oriented Programming, Encapsulation hides data and behaviour from other classes to separate responsibilities or concerns.