IB COMPUTER SCIENCE | B3.1.5 Encapsulation and Information Hiding

Lesson objective

Explain and apply encapsulation and information hiding, using controlled access, suitable operations and validation to preserve object state and clear interfaces.

Learn

B3.1.5 | ENCAPSULATION AND INFORMATION HIDING

01 | A VALID START IS NOT ENOUGH

The previous Device class started with a battery percentage from 0 to 100. However, if callers can assign device.battery = -500 directly, a valid constructor does not keep the object valid for the rest of its life.

Encapsulation and information hiding help define how other code interacts with state. The aim is a clear interface that preserves the object’s rules and avoids dependencies on unnecessary internal details.

This common SL/HL lesson explains both concepts and applies controlled operations, Java public/private access and Python conventions and properties. It also identifies what these mechanisms do not guarantee about a complete system’s security.

02 | ENCAPSULATION AND INFORMATION HIDING

Concept Main idea Device application
Encapsulation Organize related state and behaviour together in a class with a defined interface Keep battery state with use_power and recharge
Information hiding Conceal representation/implementation details behind that interface Callers need not know how charge is stored internally

The concepts support each other but emphasize different things. Putting fields and methods in a class groups them; exposing every detail for unrestricted external editing still leaves strong implementation dependencies.

A useful explanation connects structure to effect: callers request a valid operation rather than reproduce or bypass the state rules themselves.

03 | WRITE THE INVARIANT FIRST

Our invariant is that battery is an actual integer percentage from 0 to 100. device_id is nonempty identifying text. Construction and every supported update should leave those conditions true.

use_power(amount) accepts non-negative integer percentage points only when the device has enough charge. Success returns True and reduces charge; rejection returns False without changing it. recharge restores 100 and returns no explicit value.

These are teaching rules, not a physical battery model. ID uniqueness across devices, authorization and persistent storage are outside this single object’s contract.

04 | SEE THE PROBLEM WITH UNRESTRICTED STATE

class OpenDevice:
    def __init__(self, battery):
        self.battery = battery

device = OpenDevice(80)
device.battery = -500
print(device.battery)

The output is -500. The class grouped the value with initialization, but no supported boundary prevented the caller’s later assignment.

If three screens each update battery directly, each must remember the same validation rules. A missed check can create state that other methods assume cannot occur.

Moving the rule into controlled operations reduces duplicated responsibility and makes the accepted transitions easier to test.

05 | PUBLIC AND PRIVATE: JAVA ACCESS MODIFIERS

Modifier Intended use in this example Effect
public Operations offered to callers Callable where the containing type is accessible
private Internal fields and helper operations Accessible only in the permitted enclosing/nest context under Java rules
protected Selected subclass/package collaboration Broader than private; precise package/subclass rules matter
No explicit modifier Package access in Java Not the same as public

For the core example, make battery private and offer public operations. A caller outside the private access context cannot directly assign that field through normal Java member access.

Access visibility is independent of static versus instance ownership. A field can be private static or private non-static.

06 | PYTHON USES CONVENTIONS RATHER THAN JAVA PRIVATE

A leading underscore, such as _battery, signals a non-public implementation detail by convention. Python does not enforce Java-style private access for it. Cooperating callers should use the documented interface.

A double-leading-underscore name such as __battery triggers name mangling in an ordinary class definition. This helps avoid accidental name clashes, especially with subclasses; it is not an unbreakable secrecy mechanism.

Do not tell users that an underscore prevents malicious access. The practical benefit is an explicit interface boundary and fewer accidental dependencies.

07 | A READ-ONLY PUBLIC PROPERTY

class Device:
    def __init__(self, battery):
        self._battery = battery

    @property
    def battery(self):
        return self._battery

device = Device(80)
print(device.battery)
try:
    device.battery = -500
except AttributeError:
    print("No public battery setter")

The outputs are 80 and No public battery setter. @property makes the getter available using attribute syntax, device.battery. With no property setter, normal assignment to battery is rejected.

The property’s backing field _battery remains accessible to code that bypasses the intended convention. This example demonstrates a public interface restriction, not tamper-proof storage.

This short class omits constructor validation to isolate property behaviour. The complete class next validates initial state as well.

08 | APPLY CONTROLLED OPERATIONS IN PYTHON

class Device:
    def __init__(self, device_id, battery=100):
        if not isinstance(device_id, str) or not device_id.strip():
            raise ValueError("Device ID required")
        if type(battery) is not int or not 0 <= battery <= 100:
            raise ValueError("Battery must be an integer from 0 to 100")
        self._device_id = device_id.strip()
        self._battery = battery

    @property
    def device_id(self):
        return self._device_id

    @property
    def battery(self):
        return self._battery

    def use_power(self, amount):
        if type(amount) is not int or amount < 0 or amount > self._battery:
            return False
        self._battery = self._battery - amount
        return True

    def recharge(self):
        self._battery = 100

The public properties allow observation of ID and battery. No public setters are supplied. use_power and recharge are the intended mutation paths, so the battery rule is defined in one place.

A caller can still read device.battery without knowing whether the backing field is called _battery. The property is part of the interface; its backing field is an implementation detail.

Validation checks exact int type here, deliberately rejecting Boolean and text values. Accepted and rejected updates have explicit, different outcomes.

09 | USE THE INTERFACE AND CHECK THE RESULT

class Device:
    def __init__(self, device_id, battery=100):
        if not isinstance(device_id, str) or not device_id.strip():
            raise ValueError("Device ID required")
        if type(battery) is not int or not 0 <= battery <= 100:
            raise ValueError("Battery must be an integer from 0 to 100")
        self._device_id = device_id.strip()
        self._battery = battery

    @property
    def device_id(self):
        return self._device_id

    @property
    def battery(self):
        return self._battery

    def use_power(self, amount):
        if type(amount) is not int or amount < 0 or amount > self._battery:
            return False
        self._battery = self._battery - amount
        return True

    def recharge(self):
        self._battery = 100

device = Device("D01", 80)
print(device.battery)
print(device.use_power(20))
print(device.battery)
print(device.use_power(90))
print(device.battery)
device.recharge()
print(device.battery)

Outputs: 80, True, 60, False, 60, 100. The failed request for 90 does not reduce the 60 remaining charge. The caller uses returned success to decide what to display next.

recharge changes the state to 100; its Python return value is None. A method can mutate state without returning that state, but callers need a clear contract.

10 | INTERACTIVE: REQUESTS VERSUS DIRECT ASSIGNMENT

Try the supported operations on a virtual Device. Direct assignment to the public read-only property is rejected; use_power can succeed or return False. The model follows the Python class shown above, without access to its backing field.

Try 20, then 90, then −1. An ordinary direct assignment is rejected even if the proposed value is 50: this design has no public setter at all. Recharge is a deliberate method, not a way for callers to write arbitrary charge values.

11 | GETTERS NEED NOT EXPOSE EVERYTHING

A getter returns an observation of state. Returning a number or immutable string is different from returning the internal mutable collection itself.

For a ReadingLog, returning self._readings gives callers a reference to the same list. They could append an invalid reading without calling the validated add_reading method.

Return an immutable snapshot such as tuple(self._readings), or a suitable copy, when callers only need to inspect values. A shallow snapshot protects the outer structure, not necessarily mutable objects nested within it.

12 | PROTECT A COLLECTION AT THE BOUNDARY

class ReadingLog:
    def __init__(self):
        self._readings = []

    def add_reading(self, value):
        if type(value) is not int or not 0 <= value <= 100:
            return False
        self._readings.append(value)
        return True

    def get_readings(self):
        return tuple(self._readings)

log = ReadingLog()
log.add_reading(80)
snapshot = log.get_readings()
log.add_reading(60)
print(snapshot)
print(log.get_readings())

Outputs: (80,) and (80, 60). The first tuple is a snapshot, not a live mutable reference to the internal list. The stored elements are integers, so this simple immutable outer snapshot is sufficient for the example.

Copies and snapshots have a time and memory cost. Choose an interface that protects required state without blindly copying large datasets on every call.

13 | A SETTER CAN VALIDATE A PROPERTY

class Volume:
    def __init__(self, level):
        self.level = level

    @property
    def level(self):
        return self._level

    @level.setter
    def level(self, value):
        if type(value) is not int or not 0 <= value <= 10:
            raise ValueError("Volume must be an integer from 0 to 10")
        self._level = value

volume = Volume(5)
volume.level = 8
try:
    volume.level = 11
except ValueError:
    print("Rejected")
print(volume.level)

Outputs: Rejected, then 8. The initializer uses the same validated property assignment, and the setter checks before changing _level, preserving the old value on rejection.

A property setter can be appropriate when arbitrary valid replacement values make sense. It is not automatically the best interface for operations such as borrowing a book, submitting an exam or withdrawing a resource, where a domain action communicates the rule better.

14 | DO NOT ADD SETTERS JUST TO TICK A BOX

A public setSubmitted(False) could let a caller reopen a supposedly final quiz attempt. A public setBorrower(...) could bypass availability checks. Getters and setters do not automatically produce good encapsulation.

Prefer a domain method such as submit() or borrow(student_id) when the action has preconditions and state effects that matter. A read-only ID can remain without a setter when changing identity is not a supported operation.

The goal is the right operations, not maximum public access with renamed methods.

15 | JAVA: PRIVATE STATE, PUBLIC OPERATIONS

public class EncapsulationExample {
    static class Device {
        private final String deviceId;
        private int battery;

        public Device(String deviceId, int battery) {
            if (deviceId == null || deviceId.trim().isEmpty()
                    || battery < 0 || battery > 100) {
                throw new IllegalArgumentException("Invalid initial state");
            }
            this.deviceId = deviceId.trim();
            this.battery = battery;
        }

        public String getDeviceId() {
            return deviceId;
        }

        public int getBattery() {
            return battery;
        }

        public boolean usePower(int amount) {
            if (amount < 0 || amount > battery) {
                return false;
            }
            battery = battery - amount;
            return true;
        }

        public void recharge() {
            battery = 100;
        }
    }

    public static void main(String[] args) {
        Device device = new Device("D01", 80);
        System.out.println(device.usePower(20));
        System.out.println(device.usePower(90));
        System.out.println(device.getBattery());
        device.recharge();
        System.out.println(device.getBattery());
    }
}

Outputs: true, false, 60, 100. Ordinary callers outside the permitted private access context use public operations rather than editing battery directly. Java access rules permit private access within an enclosing nest; the nested demonstration is not a separate hostile caller.

The public methods enforce state rules. A field being private does not stop a wrongly written method from storing invalid values, so both visibility and method logic matter.

16 | PRIVATE HELPERS CAN HIDE INTERNAL STEPS

A Java class may keep a helper method private when it is an internal step rather than an operation callers should depend on. Public methods can use that helper without exposing it in the external interface.

Python often uses a leading underscore on a helper for the corresponding non-public intent. Its exact implementation can change while the public operation keeps the same contract.

Do not make every method public merely to make testing easy. Test observable contracts; private details can be refactored without requiring every external test to mirror them.

17 | DOUBLE UNDERSCORES ARE NAME MANGLING

class Example:
    def __init__(self):
        self.__value = 7

example = Example()
print(example._Example__value)

The output is 7. Within the class definition, __value is transformed to a name incorporating the class name. This illustrates why Python double-underscore attributes are not an absolute security boundary.

Their purpose includes reducing accidental clashes with subclass names. Do not routinely access mangled names as part of an application interface; the example exposes the mechanism to correct a misconception.

18 | CHANGE REPRESENTATION WITHOUT CHANGING CALLERS

Suppose a future device internally stores charge units from 0 to 1,000 instead of whole percentage points. If callers directly depend on _battery, the change can spread throughout the program.

A battery property and well-defined use_power contract can translate between internal units and the public percentage interface. Callers need not change if the same visible behaviour is preserved.

Define rounding and conversion carefully: keeping the method name alone is not enough. Information hiding helps change internal representation, but behavioural compatibility still requires tests.

19 | UML VISIBILITY AND THE PUBLIC CONTRACT

Device

- deviceId: String

- battery: Integer

+ getBattery(): Integer

+ usePower(amount: Integer): Boolean

+ recharge()

Minus marks private implementation state; plus marks intended public operations. This operation-style design maps to Java getters or a suitable Python property interface.

The diagram communicates access intent, while the contracts supply range rules, rejection behaviour and initialization. Visibility does not describe whether a member is static; that is a separate notation and ownership decision.

20 | SECURITY: A CONTRIBUTION, NOT A COMPLETE SYSTEM

Restricting supported access paths reduces accidental corruption and can support disciplined state handling. That is a useful contribution to object integrity.

It does not authenticate users, authorize a recharge, encrypt saved data, stop all runtime introspection or make simultaneous operations transaction-safe. Those requirements belong to additional layers of the application.

For example, a public recharge method may preserve battery bounds but still be called by the wrong user unless the surrounding service checks permissions. Valid state and authorized action are different questions.

21 | CONSTRUCT AN ENCAPSULATED QUIZ ATTEMPT

class QuizAttempt:
    def __init__(self, student_id):
        if not isinstance(student_id, str) or not student_id.strip():
            raise ValueError("Student ID required")
        self._student_id = student_id.strip()
        self._score = 0
        self._submitted = False

    @property
    def score(self):
        return self._score

    @property
    def submitted(self):
        return self._submitted

    def add_marks(self, marks):
        if self._submitted or type(marks) is not int or marks < 0:
            return False
        self._score = self._score + marks
        return True

    def submit(self):
        if self._submitted:
            return False
        self._submitted = True
        return True

attempt = QuizAttempt("S01")
attempt.add_marks(4)
attempt.submit()
print(attempt.add_marks(2))
print(attempt.score, attempt.submitted)

Outputs: False, then 4 True. Callers can observe score and submitted, but the intended interface offers no arbitrary setter for either. Once submitted, add_marks rejects further changes.

This simplified example has no maximum score and no reset operation because those were not required. Python non-public conventions still apply to the backing fields.

22 | TEST THE INVARIANTS, NOT JUST THE OUTPUT

class Device:
    def __init__(self, device_id, battery=100):
        if not isinstance(device_id, str) or not device_id.strip():
            raise ValueError("Device ID required")
        if type(battery) is not int or not 0 <= battery <= 100:
            raise ValueError("Battery must be an integer from 0 to 100")
        self._device_id = device_id.strip()
        self._battery = battery

    @property
    def device_id(self):
        return self._device_id

    @property
    def battery(self):
        return self._battery

    def use_power(self, amount):
        if type(amount) is not int or amount < 0 or amount > self._battery:
            return False
        self._battery = self._battery - amount
        return True

    def recharge(self):
        self._battery = 100

device = Device("D01", 80)
assert device.use_power(20) is True
assert device.battery == 60
assert device.use_power(90) is False
assert device.battery == 60
assert device.use_power(-1) is False
assert device.battery == 60
try:
    device.battery = 50
except AttributeError:
    pass
else:
    raise AssertionError("Expected read-only public property")
device.recharge()
assert device.battery == 100

With assertions enabled, a passing run produces no output. Check initial bounds, accepted updates, rejected updates without mutation, property access and recharge.

For mutable collections, test that the returned observation cannot mutate the internal structure through the supported interface. Also test independent instances so one device’s operations do not change another’s state.

23 | EXPLAIN THE MAINTENANCE BENEFIT

When one validated operation owns an update rule, a policy change can often be implemented in one place. Callers continue to request use_power or submit through the same contract rather than duplicate its checks.

Information hiding can limit how far an internal storage change spreads. Tests of public behaviour provide evidence that the replacement preserves the required results and state transitions.

These benefits depend on callers respecting the interface and on a sensible class responsibility. Excessive wrappers with no useful rule can make code harder to navigate instead of improving it.

24 | CHOOSE AN INTERFACE FOR A SCENARIO

A school loan object must reject a second active borrower and accept a return only when a loan exists. Decide whether a public arbitrary borrower setter is sufficient.

Reveal a justified interface

Keep borrower state non-public and offer borrow(student_id), return_book() and an availability query. A successful borrow records one borrower; a rejected request preserves the existing borrower. Returning clears state only under the documented rule.

An unrestricted setter could overwrite a current borrower or clear a loan without the intended return process. If a setter enforces all relevant rules it may preserve integrity, but domain actions usually communicate these transitions more clearly. Student existence, authorization and persisted multi-user updates still need application-level handling.

25 | COMMON CONFUSIONS TO REPAIR

Confusion More precise account
Encapsulation is only putting data in a class The design also defines meaningful state/behaviour boundaries
Information hiding means users never see output Hide implementation details while exposing required observations
Every field should have a setter Expose only the supported valid operations
A Python underscore enforces Java private It signals non-public intent by convention
Double underscores make values secret Name mangling does not provide absolute secrecy
A getter always protects state Returning a mutable internal object can leak update access
Private fields alone guarantee valid values Methods must still validate and preserve invariants
Access modifiers replace permissions and transactions Authorization and coordinated persistence are separate concerns

26 | EXPLAIN AND APPLY, WITH CAUSE AND EFFECT

For Explain, connect the access design to its consequence: “the class rejects an unaffordable use_power request before mutation, therefore battery stays within its valid range and callers cannot accidentally create a negative value through that operation.”

For Apply, construct the actual fields, public operations and validation logic for the scenario. Define initialization, success, rejection and observation behaviour, then test the state after each path.

The next lesson develops inheritance for multiple classes and is HL only. Keep interface contracts and access boundaries in mind when considering what subclasses may reuse.

MATCH THE ACCESS-DESIGN IDEA

Terminology

Terminology

Encapsulation

Organizing related state and behaviour within a class and a defined interface.

Information hiding

Keeping representation and implementation details behind an interface.

Invariant

A property that should remain true for valid object state.

Public interface

The supported operations and observations offered to callers.

Private member

A member whose access is restricted by language rules such as Java private.

Public member

A member available to callers under the containing type’s access rules.

Protected member

A member with package/subclass-related access in Java, distinct from private or public.

Package access

Java access applying when an appropriate member has no explicit access modifier.

Getter

An operation or property accessor returning an observation of state.

Setter

An operation or property accessor assigning a value under its defined policy.

Read-only property

A public observation interface without an ordinary assignment setter.

@property

Python decorator exposing an accessor through attribute syntax.

Backing field

The internal attribute used to store a property’s representation.

Non-public convention

An intended internal boundary signalled in Python, commonly by a leading underscore.

Name mangling

Python’s transformation of eligible double-leading-underscore class names to reduce clashes.

Validation

Checking data against accepted rules before applying an operation.

Rejection without mutation

A failed request leaving the prior valid state unchanged.

Domain operation

An action named for its purpose, such as borrow or submit.

Mutable reference leak

Exposing an internal changeable object so callers can bypass controlled operations.

Snapshot

An observation of state at one time rather than necessarily a live view.

Defensive copy

A separate structure supplied to reduce unintended modification of internal data.

Shallow copy

A new outer structure that can still share referenced nested objects.

Representation

The internal form used to store or implement a fact.

Contract

The specified inputs, results, state effects and failures of an operation.

State integrity

Preservation of required valid relationships and values.

Authorization

Deciding whether a user or actor may perform an action.

Access modifier

A language declaration controlling member/type access.

Behavioural compatibility

Preserving required observable behaviour when implementation changes.

Private helper

An internal operation supporting public behaviour without becoming a caller dependency.

Controlled mutation

Changing state only through intended operations that preserve the required rules.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which distinguish the two main concepts?
2. Which preserve the battery invariant through supported methods?
3. Which describe Java access correctly?
4. Which describe Python names correctly?
5. Which describe the Device battery property?
6. Which getter designs can protect an integer readings collection?
7. Which setter policies can preserve valid state?
8. Which favour a domain operation rather than an unrestricted setter?
9. Which are outside what private fields alone guarantee?
10. Which support maintainable information hiding?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Explain the difference between encapsulation and information hiding.

2. Explain how use_power preserves the battery invariant.

3. Apply public and private access to a Java Device design.

4. Distinguish Python leading-underscore convention from Java private.

5. Explain the purpose and limitation of Python name mangling.

6. Trace Device at 80 through use_power(20), use_power(90) and recharge.

7. Explain why a getter returning the internal readings list can weaken encapsulation.

8. Construct a safe public observation for an integer readings list.

9. Explain why every field does not need a public setter.

10. Explain how information hiding can help change internal charge units.

11. Evaluate the claim that an encapsulated object is automatically secure.

12. Construct a testing plan for an encapsulated stateful class.

APPLY AND EXPLAIN | LIBRARY STATE BOUNDARIES

Apply encapsulation to a library copy: expose availability and controlled borrow/return operations, reject a second active borrower and preserve the first borrower. Explain why an unrestricted borrower setter and a live mutable internal-history getter could weaken the design.

Reveal an approach

Keep borrower and history non-public. borrow(student_id) checks the required input and availability before storing; rejection leaves the first borrower unchanged. return_book() performs only the permitted transition. Availability and a suitable immutable history snapshot provide observation without arbitrary updates. A raw setter could bypass the loan rules, and a shared mutable history list could be edited without validation. Python underscores communicate intent; Java access modifiers provide language-level restrictions. Authorization and coordinated persistent updates remain separate responsibilities.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

Selections are kept while this page is open.

Workbook

Workbook

COMING SOON

The workbook for B3.1.5 Encapsulation and Information Hiding is coming soon. Complete the matching task and written questions in your exercise book.