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
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
- 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
- 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
- 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
- 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
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- State the rule and preconditionsAssume 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.
- Use the interfaceThe 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.
- Trace the requestsWith 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.
Worked example
Trace cancellation at capacity
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- Check the full-room caseThe 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.
- Check the other caseAt 2 remaining seats, the room is not full. The cancellation is allowed, so the method increases the count to 3 and returns True.
- Connect method and ruleThe 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.
Worked example
Choose a class responsibility
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- Assign the responsibilityAssume 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.
- Trace a requestSuppose 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.
- Use the interfaceA 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.
Common mistakes and how to avoid them
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
- The remaining count stays 0.
- The remaining count becomes 1.
- The remaining count becomes negative.
- The object deletes its capacity.
Show answer and explanation
Question 2
- Store the count with a borrow() method that checks availability before decreasing it.
- Let every caller change the count and ask the Book class to display the title.
- Store the count in an unrelated class with no borrowing method.
- Remove the count and let callers guess whether a copy is available.
Show answer and explanation
Question 3
- False; 3
- True; 4
- True; 2
- False; 2
Show answer and explanation
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.