AlgoViz

Encapsulation

easy 35 min

Put the data and the methods that work on it into one unit, and let outside code reach the data only through those methods.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:51

Encapsulation

1:03Reel

Theory

Read or listen first. About 2 min.

What it is

Encapsulation has two halves. Bundling: data and the methods that work on it live in one unit, usually a class. Hiding: code outside the unit cannot reach the data directly. It asks through a small public list of methods, the interface.

The word comes from capsule. A medicine capsule keeps the powder inside a smooth shell. You do not touch the powder, you swallow the capsule. A class is the shell: public methods outside, private data inside.

Hiding is not secrecy. Everybody may read the source code. Hiding means that no other code depends on the hidden part, so the hidden part can change.

Why it exists

Rules stay true. A balance that only deposit and withdraw can touch obeys the rules of these two methods. A public balance obeys nobody.

One place to change. A new fee, a log line, a daily limit: one method changes, and every caller gets it.

Freedom inside. Today the balance is a number. Next year it is a sum of ledger entries. Callers never knew, so they need no change.

Less to learn. A user of the class reads four method names and not forty fields.

A short history

  1. 1967

    Ole-Johan Dahl and Kristen Nygaard present class and subclass declarations for Simula 67. Data and procedures live together in an object.

  2. 1972

    David Parnas publishes On the Criteria To Be Used in Decomposing Systems into Modules. A module should hide one design decision from all others.

  3. 1974

    Barbara Liskov and Stephen Zilles publish Programming with Abstract Data Types. A type is known by its operations, not by how it is stored.

  4. 2017

    Java 9 changes the inside of String from a char array to a byte array plus a flag (JEP 254). The public interface stays the same, so programs do not notice.

  5. 2022

    ECMAScript 2022 brings private fields written with #, checked by the engine itself.

Words to know

Interface (of a class)
Everything outside code may use: public methods, their arguments, results and errors.
Implementation
Everything else: fields, helper methods, algorithms.
Access modifier
A word or mark such as private that says who may name a member.
Accessor
A method that reads (getter) or writes (setter) one value.
Information hiding
The reason behind it: keep a decision in one place so that it can change.
Invariant
A sentence about an object that is always true between calls, such as: the balance is never negative.
Data transfer object
A plain bundle of values that crosses a border. It has no rules, so it needs no hiding.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 5

Bundle. Data and its methods in one class

Understand it

Start here

One lever, one chute

Noor sells popcorn. Watch how the cart changes, and what the visitors can and cannot do.

The popcorn cart

The glass is not there to keep a secret. You can see through it. It is there so that nobody depends on the pan.

A piggy bank is the same idea in one object. Coins go in through the slot (deposit). You shake it to count (balance). You cannot reach in and take whatever you like: the coins are private data.

The smell

What a public field costs

Python
class BankAccount:    def __init__(self):        self.balance = 0.0account = BankAccount()account.balance = 100.0account.balance = -1_000_000.0      # nobody says noaccount.balance = "a lot"           # nobody says no to this eitherprint(account.balance)
The class has data and no opinion about it.
Edit and run it in your browser

The line that breaks the balance can be anywhere. The bug report says: balance is wrong. The list of suspects is the whole program.

Everybody knows the inside

BankAccount+ balance: double+ holder: String+ number: String

1/2Only data

Three public fields. The plus sign means: everybody may read and write.

depends on

Bundling is missing: the rules about the balance live outside the class that has the balance.

The account owns its rules

BankAccount- balance_cents: int- holder: str- number: str- taken_today: int+ deposit(cents)+ withdraw(cents, day)+ balance_cents: int- why_not(cents, day)

1/2Minus for private

Fields and the helper carry a minus. In UML: + public, - private, # protected, ~ package.

uses

Parts

Three things that make a capsule

  • Data hiding

    The state cannot be named from outside. So no other code can be written that depends on it.

  • Controlled access

    Public methods are the only way in. They can check, count, log and refuse.

  • Data integrity

    Because every change passes a gate, the rules are true after each call.

A request at the gate

Sarah talks to the machine, the machine to the account. Nobody but the account touches the number.

Tools

Who may name a member

Java

ModifierUMLSame classSame packageSubclass elsewhereEveryone
private-yesnonono
none (package)~yesyesnono
protected#yesyesyesno
public+yesyesyesyes
Start with private and open only when a caller needs it. Opening later breaks nobody. Closing later does.

Other languages draw the line elsewhere. How each one enforces it, and how callers get around it, is on Ensuring proper encapsulation. Here we need one fact: in Python the underscore is a request, not a lock. The Python tutorial itself says that truly private instance variables do not exist there.

Design

Three patterns for a field

PatternCodeUse when
Private, read onlyprivate field, public gettercallers show the value, and only the class changes it
Private, with a checked changeprivate field, method that checksthe value changes for a reason the class knows
Set onceprivate final, no setteridentity: number, id, date of birth

A setter with a check (setAge(a) refuses a negative number) is the smallest step up from a public field. An action such as withdraw is better, because it says what happened. See Tell, don't ask.

Which access does this field need?

Change over time

Mutable or not

Cannot change

  • Set in the constructor, final, no setters
  • Safe to share between threads
  • A rule checked once stays true
  • Examples: account number, money amount, date

Can change

  • State moves after creation: every method needs a check
  • Two threads need a lock
  • Who changed it? Keep a history if that matters
  • Examples: balance, cart, session

Encapsulation works for both. With values that cannot change it is nearly free. Immutability has the details.

The life of an account

Callers see method names. The states are the account's own business.

Judgement

When to use it, and when it is too much

Encapsulate

  • Sensitive data: balances, password checks
  • Values that need a check before they change
  • Complex insides with a simple outside
  • Code that will live long and change
  • When reading is allowed and writing is not

Too much

  • Data transfer objects without rules
  • Constants that should be public
  • A getter and a setter for every field, out of habit
  • Layers that add lines and protect nothing
  • A small helper used by one other class in the same file

A game character has health from 0 to 100. How do other classes change it?

BreaksPublic health
How
Weapons subtract, potions add.
Limit
Minus 30 and 140 appear, and dying is checked in five places.
Choose when
Never for a value with limits.
WorkssetHealth(n) with a check
How
The setter clamps to 0 and 100.
Limit
Every weapon still reads, computes and writes. Armour has to be added in each of them.
Choose when
A quick first step.
StrongtakeDamage(n) and heal(n)
How
The character applies armour, clamps, and announces its death once.
Limit
Each new reason needs a method.
Choose when
The default when the value has rules.

Mistakes

Four mistakes and their repair

MistakeWhat happensRepair
Public fieldsno check, no history, no freedomprivate, plus the actions callers need
A getter that returns the real listcallers change the inside without youcopy or view, see the page on doing it properly
No check on a changebad values travel and fail far awaycheck first, then write
Showing too muchevery public member is a promise for yearsexpose what a caller needs today

Neighbours

Encapsulation and the other pillars

Abstraction chooses what to show: the useful idea. Encapsulation guards how it is done: nobody can reach it. They usually come together. Inheritance can weaken encapsulation, because a subclass sees more than a caller. Polymorphism lets many insides answer the same call.

Summary

The whole topic in one minute.

Encapsulation bundles data with the methods that work on it and keeps other code away from the data. Rules then live in one class, errors stop at the gate, and the inside can be replaced without touching callers.

Use private fields, named actions and useful questions. Do not produce accessors by habit, and do not wrap plain values that have no rules. For leaks through references, copies and side doors read the page on doing it properly.

  • Bundle data with its methods, then hide the data.
  • Private by default. Open on demand, because closing breaks callers.
  • Offer actions and questions, not one getter and setter per field.
  • Every change passes one gate: check, then write.
  • The reward is freedom: the inside may change and no caller notices.
  • No rule inside? Then a plain record is the honest choice.

Sources