Encapsulation protects a rule
Design objects around valid state and meaningful operations.
What you’ll learn
- Define a useful invariant
- Place validation with the state owner
- Distinguish encapsulation from automatic getter generation
Begin with a rule worth preserving
Consider a workshop with a fixed number of seats. Its reservation count must never be negative and must never exceed capacity. That condition is an invariant: it should hold after construction and after each public operation finishes. The object design should make this rule easy to preserve. Starting with the rule gives the class a purpose. Starting only with a list of fields often produces a data container that lets every caller change the count in a different way.
Hide representation for a reason
Making a field private prevents direct access through the public interface, but access control alone does not establish a useful contract. If an unrestricted public setter accepts any reservation count, the invariant can still be broken through an officially supported operation. Encapsulation combines a hidden representation with operations that preserve the intended behavior. The representation may later change from a stored count to a set of reservation records without forcing callers to duplicate its internal logic.
Offer domain actions
An operation named reserveSeat describes an intention more clearly than setCount. It can check whether a seat is available, apply the update, and report a full result without exposing the update sequence to every caller. Decide how failure is communicated: a result value, an exception, or another explicit mechanism may fit the language and application. The important point is that callers can understand the outcome and that an unsuccessful action does not leave the object half-updated.
In the Python example, a leading underscore marks _entries as an implementation detail by convention; it does not enforce private access. The record() method is the intended public operation and keeps validation in one place.
class ReadingLog:
def __init__(self):
self._entries = []
def record(self, pages):
if pages < 0:
raise ValueError("pages must be non-negative")
self._entries.append(pages)
def total(self):
return sum(self._entries)
log = ReadingLog()
log.record(12)
print(log.total()) # 12Keep boundaries and concurrency visible
A well-designed object does not automatically make a concurrent system safe. Two callers may both observe one remaining seat before either commits its update. In a single-process program you may need synchronization; across application instances you may need a transactional storage operation or another coordination mechanism. The invariant still guides the design, but its enforcement must cover the actual state-sharing boundary. Do not claim a private field solves a race between independent processes.
Test observable transitions
Test construction with ordinary and invalid capacity values, then reserve seats until the boundary is reached. Check that another reservation is rejected and that a cancellation follows the documented rule. Tests should focus on outcomes visible through the public contract rather than the arrangement of private fields. Include repeated requests if they are possible in the application. This produces a model that can be reviewed in terms of rules and behavior, which is more useful than counting classes or getters.
Try it yourself
A public setter accepts negative inventory. Explain why a private inventory field has not solved the design problem.
Show a possible solution
The public operation still permits an invalid state. Replace the unrestricted update with operations that express inventory changes, validate their inputs, and preserve the documented invariant. If updates are concurrent, enforce the rule at the actual shared-state boundary.
Check your understanding
Try 14 questions across object-oriented design. Read each explanation and revisit anything that needs another pass.
Practise this subjectGo to the source
Use these primary references to check details and explore the topic further.
Saved in this browser. Signed-in progress syncs to your account.