Search Sreeni's Insights

Filter by content type
technical August 9, 2011 13 min read

What is encapsulation? - Part 4

This article explains encapsulation as responsibility and trust, showing how a bill object protects its state while exposing useful operations to the grocery billing system.

Share:

What is encapsulation? - Part 4

Ask any beginner what is encapsulation, the answer will be “make the fields private and add getters and setters”. It is the most common answer in interviews also. But a class where every field has a public getter and setter is not protecting anything, anybody can still change anything, only the path is longer. Encapsulation is not a programming trick, it is how the real world builds trust. We don’t fly the aeroplane ourselves, we don’t count the cash in the bank’s locker room and we don’t open the back of our wrist watch, we trust someone who is responsible for it. Encapsulation is about responsibility and trust, an object takes the responsibility of its own state, so that nobody else can put it into a wrong state. In the previous article, we discussed abstraction, what to show to the outside world. In this article, we are going to see what is encapsulation, first in the real world and in philosophy, then how it works together with abstraction, and finally as a principle of object-oriented thinking, information hiding, invariants and the “tell, don’t ask” idea.

Object-Oriented Thinking series:

  1. How to model the real world with objects? - Part 1
  2. How do we organize what we know? - Part 2
  3. What is abstraction? - Part 3
  4. What is encapsulation? (this article)
  5. What is inheritance? - Part 5
  6. What are subtype and subclass polymorphism? - Part 6
  7. How objects relate to each other? - Part 7
  8. How all these concepts connect? - Part 8

TL; DR Summary

  • Encapsulation is keeping the state and the behaviour which works on that state together, and allowing the outside world to use the object only through its behaviour.
  • In the real world, encapsulation is about responsibility and trust, whoever is responsible for something must also control it.
  • It bundles things together, hides the inner details, protects them and controls who can access them.
  • Encapsulation hides complexity, abstraction simplifies it. They are related but different, and they complement each other.
  • Information hiding is the reason behind encapsulation, hide the decisions which are likely to change.
  • An object is responsible for keeping its own state valid, these rules are called invariants.
  • Private fields with public getters and setters for everything is not encapsulation. Tell the object what to do, don’t ask for its data and do the work outside.

Common Challenges

Anybody can change anything

Let us take our bill. If the list of items and the total are open to everyone, the billing screen can add an item without updating the total, the report can reset the total to zero and the discount module can apply the discount twice. Each part thinks it is doing the right thing. As a result of this, the customer gets a bill where the items don’t match the total, and it is very hard to find which part of the program changed it.

The same rule in many places

When the state is open, the rules about it are written by whoever is using it. “The quantity must be more than zero” is checked in the billing screen, again in the mobile app and forgotten in the bulk upload. When the rule is changing, for example, the maximum quantity per customer during a festival offer, we have to change it in all places, otherwise some places allow it and some don’t.

Encapsulation in the real world and in philosophy

The word comes from “capsule”, which comes from the Latin “capsula”, a small box. A medicine capsule keeps the medicine inside a cover, we take the capsule, we don’t handle the powder directly. Let us discuss the different faces of encapsulation, without any computer.

Encapsulation is about responsibility and trust

When we board an aeroplane, we don’t go to the cockpit and check the fuel. We trust the pilot, the airline and the engineers. This trust works only because the responsibility is clear and the control is with the responsible person. The pilot is responsible for the flight, and nobody else is allowed to touch the controls.

The management thinker Henri Fayol, in 1916, listed “authority and responsibility” as one of his principles of management, they must always go together. Responsibility without control is unfair, the person is blamed for what others did. Control without responsibility is dangerous, the person can change things without answering for them. Encapsulation is exactly this balance, whoever is responsible for something must also be the only one who controls it.

Encapsulation is bundling together

A living cell is the most beautiful example of encapsulation in nature. The cell membrane keeps everything the cell needs together, the material and the machinery which works on that material. The cell doesn’t keep its material in one place and its machinery in another place, they live together inside the same boundary.

It means, encapsulation is first about bundling, the things and the actions on those things belong together in one unit.

Encapsulation is hiding the inner details

A wrist watch shows us only the hands and the dial. Inside, there are gears, springs or a battery and a quartz crystal, and the case is sealed. Most of the watch companies say the warranty is void if we open the case ourselves. We don’t need to know whether it is mechanical or quartz to read the time, and the watch maker can change the inside mechanism in the next model without teaching us how to read the time again.

This is encapsulation hiding complexity. The complexity is still there, but it is kept inside a boundary, where only the responsible person deals with it.

Encapsulation is protecting what is inside

Our skin protects the organs from dust, germs and injury. Nobody can directly change the beating of our heart from outside, the heart regulates itself and the body controls it. If the heart could be changed by anybody passing by, we would not live for one day.

Protection is not about being secret, everybody knows we have a heart. It is about making sure nobody from outside can put it into a wrong state.

Encapsulation is controlling access

A house has a front door for the guests, a bedroom for the family and a locker for the owner only. Different people have different access, and the owner decides it. A pharmacy is a better example. We don’t go behind the counter and take the medicines from the shelf. We ask the pharmacist, he checks the prescription and the dosage, and only then gives the medicine. The access is not denied, it is controlled, and the control is with the one who knows the rules.

Encapsulation is data hiding

In an election, we cast the vote in secret, and nobody can see whom we voted for. Our medical records are seen only by our doctor. A letter is sent in a sealed envelope. Some information is not for everyone, and hiding it is what protects the person it belongs to. In society, we call it privacy.

So, what is encapsulation in real life?

Based on the above, find below the faces of encapsulation we have seen,

  • Responsibility and trust - Whoever is responsible must also have the control (the pilot).
  • Bundling - The things and the actions on them live together (the cell).
  • Hiding details - The inner mechanism is behind a boundary (the watch).
  • Protection - Nobody from outside can put it into a wrong state (the heart).
  • Controlled access - You ask, the responsible one decides (the pharmacist).
  • Data hiding - Some information is visible only to its owner (the secret vote).

Again, these are not six different ideas. They are six views of one idea, a thing with a clear boundary, which takes care of itself and can be trusted by others because of that.

Abstraction and encapsulation in the real world

Abstraction and encapsulation are always confused, because in real life they always appear together. Let us take the car once again. The following diagram depicts the same car from the two ideas. On the left, abstraction decides what the driver sees, the steering wheel, the pedals, the gear and the gauges. On the right, encapsulation keeps the engine, the fuel injection and the wiring under the bonnet, closed and opened only by the mechanic. Each control reaches its hidden part only through a fixed connection, the agreed interface, the steering wheel to the steering system, the accelerator to the engine, the brake to the brake system and the gear lever to the gearbox. The gauges work the other way, the sensors under the bonnet send the reading to the driver.

Abstraction and encapsulation in a car
Abstraction and encapsulation in a car

Here is how these two ideas are related,

  • Related but different - Abstraction is about what we see, it simplifies. Encapsulation is about what we can touch, it hides and protects. The steering wheel is an abstraction of the direction system, the bonnet is the encapsulation of the engine.
  • They complement each other - An abstraction without encapsulation can be bypassed, if the bonnet is open while driving, anybody can pull a wire and the steering wheel is not the only way to control the car. An encapsulation without a good abstraction is useless, a sealed car with no steering wheel is safe but nobody can drive it.
  • Both manage complexity at scale - A city of millions works because every department has a simple counter (abstraction) and keeps its files and processes inside (encapsulation). The citizen doesn’t need to know how the water department works internally, and the water department can change its internal process without asking every citizen.
  • Both make things maintainable and reusable - Because the driver depends only on the steering wheel and the pedals, he can drive any car, which is reuse. Because the engine is behind the bonnet, the company can improve the engine in the next model without changing how people drive, which is maintainability.

Hold these four points, we will see all of them again in software in the next sections.

What is encapsulation in object-oriented thinking?

Encapsulation is the principle of bundling the data (state) and the operations (behaviour) which work on that data into a single unit, the object, and restricting the direct access to the data from outside, so it can be changed only through the object’s behaviour.

In simple terms, the object is the only one who can touch its own data, others must ask it. Just like the cell, the data and the behaviour live together. Just like the pharmacist, the object decides what is allowed.

Let us take an analogy, a bank. We don’t walk into the bank’s locker room and take the money from the shelf. We go to the counter or the ATM and ask “withdraw 2000”. The bank checks the balance, the daily limit and the account status, then gives the money and updates the balance. The bank is responsible for the correctness of its accounts, and that is exactly why we trust it.

The following diagram depicts encapsulation of our bill. The billing screen and the daily report use only the public behaviour of the bill, like addItem() and getTotal(). The private state, the items and the total, is inside the object and nobody from outside can change it directly. Only the bill’s own behaviour updates or reads the state, so it can check the rules every time. The red line shows the daily report trying to set the total to 0 directly, which is not allowed.

Encapsulation of a bill
Encapsulation of a bill

What is information hiding?

Information hiding is the principle of hiding the design decisions which are likely to change, behind a stable interface, so that a change in the decision does not affect the other parts of the system.

David Parnas introduced this idea in his 1972 paper “On the Criteria To Be Used in Decomposing Systems into Modules”. His point was, we should not divide the system based on the steps, we should divide it based on the decisions which may change, and hide each decision inside one module. It is the same reason the watch maker can change the mechanism without changing the dial.

In our bill, here are some decisions which are likely to change,

  • How the items are stored, a simple list today, maybe grouped by category tomorrow.
  • How the total is calculated, add all lines today, maybe with tax and rounding rules tomorrow.
  • Whether the total is calculated every time or kept ready.

If these decisions are hidden inside the bill, we can change them anytime, the billing screen and the report will not even know. If they are visible, every change becomes a change in many places. It means, encapsulation is the mechanism, and information hiding is the reason why we use it.

What is an invariant?

An invariant is a rule about the state of an object which must always be true, from the time the object is created until it is destroyed.

In the real world, our body has invariants too, the body temperature stays near 37°C whether it is summer or winter, and the body itself is responsible for keeping it. Here are few invariants of our bill,

  • The total is always equal to the sum of all bill line amounts.
  • The quantity of every line is more than zero.
  • Once the bill is paid, no item can be added or removed.

The most important job of encapsulation is to protect these invariants. When the only way to add an item is through the addItem behaviour of the bill, the bill can check the quantity, update the total and refuse if it is already paid, all in one place. Nobody from outside can break these rules, because nobody from outside can touch the state directly.

Must Do: For every object, write down its invariants before deciding its behaviour. Every behaviour must leave the object in a valid state, otherwise the object cannot be trusted.

Why getters and setters for everything is not encapsulation?

Based on the above, you may be wondering, “my fields are private, so my class is encapsulated, right?”. Not really. If every field has a getter and a setter, the outside world can still read everything and set anything, the setter for total allows anyone to set the total to any value, and the invariant “total equals the sum of lines” is broken again. It is like a pharmacy which keeps the medicines behind the counter, but gives every customer whatever he asks for without checking the prescription. Only the syntax is changed, the thinking is still procedural, the data is in one place and the logic is outside.

Ask the following questions for every getter and setter,

  • Does the outside world really need this information? If not, don’t expose it.
  • Should anyone be able to set this value directly? Most of the time, the value should change only as a result of a business action, like “add item” or “apply discount”, not “set total”.
  • Is there a rule about this value? Then the rule belongs to the object, not to the caller.

Tell, don’t ask

“Tell, don’t ask” is a guideline which says, instead of asking an object for its data and taking the decision outside, tell the object what you want and let it decide. It was popularized by Andy Hunt and Dave Thomas, the authors of The Pragmatic Programmer. We tell the bank “withdraw 2000”, we don’t ask for the balance and update it ourselves.

Example:

Ask style, the logic is outside the bill,

if bill.status is not Paid
    and quantity > 0 then
        bill.items.add(item, quantity)
        bill.total = bill.total + item.price * quantity

Tell style, the logic is inside the bill,

bill.addItem(item, quantity)

In the ask style, every caller must remember all the rules. In the tell style, the rules are written once, inside the bill, and every caller automatically follows them. When the festival rule “maximum 5 packets of sugar per bill” is introduced, we change only the bill.

Encapsulation vs Abstraction

We saw how these two work together in the car. Find below the quick comparison in software,

AbstractionEncapsulation
QuestionWhat should the outside world see?How do we protect what is inside?
FocusEssential behaviour and informationHiding the state and the implementation
What it does with complexitySimplifies itHides and contains it
Thinking levelDesign, from the viewer’s perspectiveImplementation, from the object’s responsibility
ExampleA bill can add items and give the totalItems and total are hidden, only addItem() can change them
AnalogyThe ATM screen shows withdraw, deposit, balanceThe cash and the account records are locked inside
Helps withReuse, many callers depend on the same simple viewMaintenance, the inside can change without affecting callers

Simply put, abstraction decides the shape of the window, encapsulation builds the wall around it. You need both, an abstraction without encapsulation can be bypassed, and an encapsulation without a good abstraction hides the wrong things. Together, they are the foundation of every object-oriented design, and the main reason large systems with many teams can still be changed safely.

Benefits of encapsulation

  • Trust - The object always stays valid, so the other objects can depend on it without checking.
  • Change - The inside can be changed without affecting the users, as long as the behaviour is the same.
  • One place for rules - Business rules live with the data they protect.
  • Easy to debug - When the state is wrong, there are only few places which can change it.

Keep in mind that encapsulation has a small cost, we have to design the behaviour carefully instead of just opening the data. It is a trade-off, but for any object which has business rules, it is highly recommended.

Wrap up

In this article, we have looked at encapsulation in the real world and in philosophy, as responsibility and trust, bundling, hiding, protection, controlled access and data hiding, how abstraction and encapsulation complement each other, and then encapsulation in object-oriented thinking, information hiding, invariants, why getters and setters for everything is not encapsulation and the “tell, don’t ask” guideline. I really appreciate that you took the time to read this article. So far, we have looked at one kind of thing at a time. In the next article, I will walk you through inheritance, how special kinds share the characteristics of a general kind, first in the real world and then in software, and when it is the right choice and when it is not.

Related Posts