DoAssignment study guide

C1.2 · Use encapsulation in program design

Learn to use encapsulation in program design through clear examples and targeted practice.

Ontario Grade 12 Computer Science

Designing Modular Programs

Keeping an object's data and the operations on it together

In ICS3U, you used variables, decisions, methods, and classes to organize programs. In this lesson, you will use encapsulation in program design: keep related data and the operations that manage it together, and let other parts of a program interact with an object through methods. This can help keep the object's data consistent. The examples use short Python 3 code for illustration; classroom languages can differ.

What you will learn

  • Explain how encapsulation groups an object's data with the methods that work on it.
  • Describe how a class can control access to its internal data through a public interface.
  • Trace simple method calls and explain how they preserve an object's rules.
  • Choose class responsibilities and methods that support a stated program requirement.

1. From related variables to an object

Suppose a program records how many seats remain in a small room. If the count is a separate variable that different parts of a program can change, one part might update it without checking whether the change is allowed. The count could become negative or exceed the room's capacity.
A class can bring together the data describing a room and the methods that perform valid actions on that data. An object made from the class keeps its own state. For this example, the state includes the room's capacity and the number of seats remaining; the actions include reserving and cancelling a reservation.
The class's public interface is the set of methods that other code is meant to use. Those methods provide a way to request actions. A caller need not know the details of how the count is stored; it needs to know which methods are available and what they do.
  • Encapsulation groups related data and methods in a class.
  • An object holds its own data, called its state.
  • A public interface gives other code a clear way to request actions.

2. Control changes through methods

A useful design starts by stating the object's rule. In the room example, the number of remaining seats must stay between zero and the room's capacity. A reservation is allowed only when at least one seat remains; a cancellation is allowed only when a reservation can be reversed.
In Python, a leading underscore in a name such as _remaining is a convention indicating that other code should treat the attribute as internal. It is not a security barrier. The design intention is that callers use the methods rather than changing the internal data directly. Methods check each requested action before updating the values.
Preconditions for the room example are that capacity is a positive whole number and that each request concerns one seat. Input is the capacity and a sequence of method requests. The algorithm stores the capacity and starting seat count, checks each request against the current values, and changes the count only if the request is allowed. Expected outputs are the Boolean result of each request and the remaining-seat count when requested.
  • State the object's rule before writing its methods.
  • Methods can check a request before changing internal data.
  • An underscore signals intended internal use in Python; it does not make an attribute truly inaccessible.

3. Design responsibilities and trace behaviour

Encapsulation is not simply placing every variable in a class. Give the class responsibility for data and actions that belong together. A caller should use the object's interface rather than reproduce its rules elsewhere. If a new action is needed, consider whether it belongs with that object's data and whether the interface can express it clearly.
Trace a method call by recording the state before the call, the check performed, and the state afterward. If a request fails its check, the state should remain unchanged. This trace helps check that the method follows the stated rule without relying on a program run.
A class diagram can show the design at a glance: the class owns its state and offers methods to other code. The diagram describes responsibilities, not a promise that every language has the same access-control features.
  • Keep a class focused on the data and actions it is responsible for.
  • For each call, check whether the request is allowed and whether state changes.
  • A failed request should not create a state that breaks the object's rule.

4. Review a design and practise

When reviewing an encapsulated design, identify the object's state, its rule, and its public methods. Then ask whether a caller can complete the required task through those methods without changing internal data directly.
A method name should communicate the requested action, and its result should make the outcome clear. For example, reserve() can return True when a seat was reserved and False when none was available. The caller can respond to the result without taking over the room's internal decision.
Encapsulation does not automatically make a program correct. The class still needs suitable rules and methods, and callers still need to use the interface as intended. The benefit is that the rules for changing the object's data are located with that data, making the design easier to understand and maintain.
For practice, sketch a class for a game character whose health cannot fall below zero. Name the relevant state and one method that should control a change. Before writing code, state what the method checks and what it returns when the request cannot be accepted.
  • Review state, rules, and public methods together.
  • Use method results to communicate whether a requested action succeeded.
  • Encapsulation supports a consistent design but does not replace careful programming.

Worked example

Reserve and cancel room seats

Design a room object that accepts one-seat reservations and cancellations while keeping the remaining-seat count within its valid range.
Room class responsibilities
ownsoffersRoom_capacity, _remainingreserve(), cancel(), rem

Room owns its seat data and offers methods that check requests.

Python 3

class Room:
    def __init__(self, capacity):
        self._capacity = capacity
        self._remaining = capacity

    def reserve(self):
        if self._remaining == 0:
            return False
        self._remaining -= 1
        return True

    def cancel(self):
        if self._remaining == self._capacity:
            return False
        self._remaining += 1
        return True

    def remaining(self):
        return self._remaining
  1. State the rule and preconditions
    Assume capacity is a positive whole number and requests concern one seat at a time. The valid remaining-seat count is from zero through capacity. The object must store both capacity and remaining seats so that its methods can check both boundaries.
  2. Use the interface
    The code offers reserve(), cancel(), and remaining(). A reservation succeeds only if a seat is available. A cancellation succeeds only if at least one seat has already been reserved. In either method, a rejected request leaves the count unchanged.
  3. Trace the requests
    With capacity 2, the first reservation succeeds and leaves 1 seat. The second succeeds and leaves 0. A third reservation fails and leaves 0. A cancellation then succeeds and leaves 1. The expected results are True, True, False, and True, followed by a remaining-seat count of 1. These values are derived by tracing the code, not by claiming it was run.
Answer: The Room object keeps its capacity and remaining-seat count with methods that enforce the rule. Callers request actions through the interface rather than changing the internal attributes directly.
Check: The count stays within the allowed range after each traced request.

Worked example

Trace cancellation at capacity

For a room with capacity 3 and 3 remaining seats, determine the result of cancel(). Then consider the same room when 2 seats remain.
Room state and controlled actions
ownsoffersRoom_capacity, _remainingreserve(), cancel(), rem

The class stores both values needed to enforce the seat-count rule.

Python 3

def cancel(self):
    if self._remaining == self._capacity:
        return False
    self._remaining += 1
    return True
  1. Check the full-room case
    The precondition is that capacity is a positive whole number and the request is to cancel one seat. At 3 remaining seats in a room of capacity 3, cancel() finds that the room is already full. It returns False and leaves the count at 3.
  2. Check the other case
    At 2 remaining seats, the room is not full. The cancellation is allowed, so the method increases the count to 3 and returns True.
  3. Connect method and rule
    The capacity value is part of the object's state because the method needs it to decide whether a cancellation is allowed. Keeping this check in cancel() means callers do not have to repeat the rule.
Answer: At full capacity, cancel() returns False and the remaining count stays 3. With 2 seats remaining, it returns True and the count becomes 3.
Check: Neither call makes the remaining count exceed capacity.

Worked example

Choose a class responsibility

A library program tracks one book's number of available copies. Decide which responsibility belongs in a Book class and trace one request to borrow a copy.
Book class responsibility
ownsoffersBook_availableborrow()

Book holds copy data and offers a controlled borrowing method.

Python 3

class Book:
    def __init__(self, copies):
        self._available = copies

    def borrow(self):
        if self._available == 0:
            return False
        self._available -= 1
        return True
  1. Assign the responsibility
    Assume the starting number of copies is a non-negative whole number. The Book class holds the available-copy count and provides a borrow() method. The borrowing rule is that the count decreases only when at least one copy is available.
  2. Trace a request
    Suppose the object starts with 2 available copies. A call to borrow() checks that the count is greater than zero, decreases it to 1, and returns True. A later call applies the same check to the updated count.
  3. Use the interface
    A caller asks the Book object to borrow a copy and uses the returned result. It does not need to decide how the Book stores its count or directly change that count.
Answer: The Book class is responsible for the available-copy data and the borrowing action that changes it according to the stated rule.
Check: Starting from 2 copies, one successful borrow leaves 1 copy available.

Common mistakes and how to avoid them

Thinking that a leading underscore makes a Python attribute impossible to access.
Correction: An underscore is a convention that signals internal use. The design relies on callers using the intended methods.
Putting data in a class but allowing callers to change it without following the object's rules.
Correction: Use methods to check requests and make valid state changes.
Adding unrelated responsibilities to one class simply because they are used in the same program.
Correction: Keep a class focused on data and actions that belong together, such as a book's available copies and borrowing action.
Assuming encapsulation by itself guarantees correct behaviour.
Correction: State the rules clearly and check that each method follows them. Encapsulation organizes where those rules are applied.

Lesson summary

  • Encapsulation brings related data and methods together in a class.
  • A class's public methods provide a controlled interface for other code.
  • Methods should check requests before changing object state.
  • Trace state before and after calls to confirm that the object's rules are preserved.

Check your understanding

Question 1

A Room object has 0 remaining seats. Its reserve() method returns False when no seats remain. What should happen to the object's state after the call?
  1. The remaining count stays 0.
  2. The remaining count becomes 1.
  3. The remaining count becomes negative.
  4. The object deletes its capacity.
Show answer and explanation
The remaining count stays 0.
The request fails the method's check, so the state should not change.

Question 2

Which design best uses encapsulation for a book's available-copy count?
  1. Store the count with a borrow() method that checks availability before decreasing it.
  2. Let every caller change the count and ask the Book class to display the title.
  3. Store the count in an unrelated class with no borrowing method.
  4. Remove the count and let callers guess whether a copy is available.
Show answer and explanation
Store the count with a borrow() method that checks availability before decreasing it.
The data and the action that changes it belong together, and the method can apply the borrowing rule.

Question 3

In a Room design that stores capacity, capacity is 3 and remaining seats are 3. What should cancel() return, and what should the remaining count be afterward?
  1. False; 3
  2. True; 4
  3. True; 2
  4. False; 2
Show answer and explanation
False; 3
At full capacity, cancellation is not allowed. The method returns False without changing the count.

Key terms

Encapsulation
A program-design approach that groups related data and methods in a class and provides an interface for using them.
Class
A program structure that describes data and methods for objects of that kind.
Object
A particular instance of a class, with its own state and available methods.
State
The current data held by an object.
Interface
The methods and expected behaviour that other parts of a program use to interact with an object.

Continue through ICS4U

View the complete ICS4U Ontario Grade 12 Computer Science curriculum and lessons

Tutor support for C1.2 · Use encapsulation in program design

Working on C1.2 · Use encapsulation in program design in ICS4U? Bring the question and your own attempt. In a live session, you can trace a small input step by step, compare expected and actual output, and test an edge case. Ask about the first step that does not make sense, then try a similar question yourself.

Explore coding tutoring · Request an eligible free 30-minute introduction. Your request is matched by subject and language; a tutor must accept before a time is confirmed.

برای مبحث C1.2 · کاربرد کپسوله‌سازی در طراحی برنامه در درس ICS4U، سؤال و تلاش خود را همراه بیاورید. در جلسه می‌توانید یک ورودی کوچک را گام‌به‌گام دنبال کنید، خروجی مورد انتظار و واقعی را مقایسه کنید و یک حالت مرزی را بیازمایید. راهنمای معلم برنامه‌نویسی را ببینید یا جلسهٔ معارفهٔ رایگان ۳۰ دقیقه‌ای درخواست کنید. زمان جلسه پس از پذیرش معلم قطعی می‌شود.

About this lesson and its review

Published by DoAssignment. This reviewed lesson follows Ontario Grade 12 Computer Science (ICS4U), expectation C1.2. It is a study resource, not an official curriculum publication.

Before publication, content is checked for structure, mathematical or chemical notation, calculations, course boundaries, and readability. Errors can still occur, so corrections are welcomed.

Official curriculum reference

Report a correction or ask a question