liveBook · Manning

Encapsulation

As explained in Software Design for Python Programmers

Implementation hiding is a software design technique that exposes only a class's necessary interface while concealing its internal representation and operations.

Encapsulation exposes only the interface that other code needs while hiding a class’s implementation. In Python, a class groups instance variables and methods, and private members restrict direct access. The broader design principle, “Encapsulate What Varies,” isolates change so implementation updates do not spread through dependent classes. section 1.8 section 5.0 section 1.10

Apply encapsulation by:

  • Making instance variables and methods private when clients do not need direct access. section 5.0
  • Exposing only the public members required by other classes. section 5.0
  • Isolating behavior likely to change so clients remain unaffected when implementation details change. section 1.10

Date implementation hiding

A Date object represents a calendar date with year, month, and day values. Keeping _year, _month, and _day private lets the class hide its representation while providing operations such as date arithmetic through its interface. Client code depends on Date’s behavior rather than on how dates are stored. section 5.3

The cost of missing encapsulation

In the poorly designed sports application, Baseball and Football both hardcode the stadium venue. If that venue changes, multiple subclasses must change; duplicated algorithms are difficult to reuse and maintain. Encapsulating varying algorithms supports looser coupling and avoids these change leaks. section 8.2.2

How Software Design for Python Programmers covers it

How deep it goes
Defines public, private, and protected members, then demonstrates change leakage through Date and sports design examples.
Examples
Uses private Date components and a sports hierarchy with duplicated venues and player-recruitment algorithms.
What it assumes
Assumes basic classes, instance variables, methods, and objects while defining member visibility and change isolation.
What you can do after
Apply it via private implementation members and a focused public interface that limits change propagation.
How it connects
Connects encapsulation with abstraction, loose coupling, inheritance, polymorphism, the Open-Closed Principle, and design patterns.

Also explained in

Compare how 14 books explain encapsulation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.