liveBook · Manning

Delegation principle

As explained in Software Design for Python Programmers

The Delegation Principle assigns work to another class whose responsibility and cohesion make it more suitable for performing that work.

The Delegation Principle moves work from a requester class into a more suitable, cohesive delegate class. The requester keeps a delegate object and asks it to perform the work without depending on its implementation. section 2.3.2

Catalogue delegates attribute matching

A Catalogue stores Book objects, while each Book contains an Attributes object. Instead of matching titles, authors, years, and genres itself, Catalogue calls book.attributes.is_match(target_attrs). Attribute changes therefore remain inside Attributes, making Catalogue more cohesive and loosely coupled. section 2.3.2

Delegation also supports the Strategy Design Pattern. Sport delegates player recruitment and venue selection to strategy objects, whose implementations can be selected by subclasses or replaced at run time. section 8.2.3

How Software Design for Python Programmers covers it

How deep it goes
Defines requester and delegate roles, demonstrates a Catalogue refactoring, and connects delegation to runtime-selectable strategies.
Examples
Uses Catalogue, Book, and Attributes for matching, then Sport with player and venue strategies for algorithm selection.
What it assumes
Assumes classes, instance variables, methods, object composition, and basic polymorphic interfaces.
What you can do after
Apply it by extracting cohesive work into delegate objects and invoking them through stable requester methods.
How it connects
Connects delegation with cohesion, loose coupling, the Principle of Least Knowledge, and the Strategy Design Pattern.

Also explained in

Compare how 2 books explain delegation principle →

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.