Lesson · Object-Oriented Python
Composition & Delegation
55 min readComposition & Delegation
Composition builds objects from collaborators instead of from parent classes. It usually reduces coupling and makes replacement, testing, and reuse easier than deep inheritance trees.
Learning goals
- Explain what
OrderService(EmailSender())builds: an object that owns a collaborator rather than inheriting from one. - Trace
place_order("A-100")through the delegation step toEmailSender.sendand read the printed line it produces. - Explain why swapping in a different sender (a logger, a fake) needs no change to
OrderService. - Distinguish a has-a relationship from an is-a relationship using the classes in the example.
- Predict what
self.sender.send(...)raises when the collaborator lacks the expected method.
Mental model
The service never knows how sending happens; it only knows the method it can call, so any object with a compatible send can replace EmailSender. That indirection is the point of delegation: policy stays in place_order, mechanism stays in the collaborator.
Mental model
read it top to bottom
order_service = OrderService(EmailSender())
↓ OrderService owns a sender: self.sender = sender (has-a, not is-a)
order_service.place_order("A-100")
↓ builds the message, then delegates
self.sender.send("order A-100 placed")
↓ the collaborator owns the actual sending behavior
EmailSender.send prints "email: order A-100 placed"Core idea
Composition builds an object from parts it holds: OrderService contains a sender and forwards work to it, instead of inheriting send from a base class. The seam is the collaborator reference self.sender, which is why a logger or a fake sender can replace the email sender without touching place_order. Delegation is how behavior crosses that seam: the wrapper adds policy and passes the operation along.
Has-a relationships
A has-a relationship means an object owns or collaborates with another object rather than being a subtype of it. This is the core idea behind composition.
Composition vs inheritance
Composition makes an object hold the behavior it needs as a collaborator; inheritance makes the object a subtype that receives the behavior through lookup. An OrderService that holds a sender can swap senders and exposes only place_order, while a subclass would expose the sender's whole interface and freeze one family of senders into the class tree. Prefer composition when the relationship is has-a and replacement or testing matters; keep inheritance for genuine is-a contracts with shared method shapes.
Delegating behavior
Delegation forwards an operation to a collaborator that owns the relevant behavior. The wrapper can add policy while keeping the specialized implementation separate.
Wrapper objects
A wrapper object holds another object and exposes its own interface on top of it, forwarding the operations it does not change; OrderService wraps a sender without exposing send directly. Wrappers are how you add policy (logging, retries, validation) while the wrapped object keeps its single job. Keep the forwarded calls thin, because a wrapper that re-implements the wrapped behavior loses the decoupling it was built for.
Designing collaborators
Designing collaborators means choosing the smallest set of operations the owner needs and accepting any object that provides them, as OrderService needs only send(message). That makes fakes and doubles trivial: a test sender is a few lines that record calls, with no base class to inherit. Document the expected behavior of each collaborator, since nothing enforces it at construction unless you add a check.
Walkthrough
OrderService(EmailSender())evaluatesEmailSender()first, then passes that instance to__init__, which stores it asself.sender; the service and the sender are two separate objects.place_order("A-100")formats the messagef"order {order_id} placed"and callsself.sender.send(...), so the work of sending is delegated to whichever object the service currently holds.EmailSender.sendreceives"order A-100 placed"and printsemail: order A-100 placed; ownership runs service then sender, and no class in the example inherits from another.- Predict before running: the printed line, what a second service built with a different sender object would print, and what error appears if the collaborator has no
send.
Experiments to try
- Swap
EmailSenderfor aLogSenderwhosesendappends to a list; confirmOrderServiceis unchanged and compare the captured message. - Run
OrderService(None).place_order("A-100")and read theAttributeError; then move the failure earlier by validatingsenderin__init__and compare the two reports. - Make
OrderServicea subclass ofEmailSenderinstead and list what breaks when you want to send both an email and a log. - Check ownership with
service.sender is senderfor the instance you passed in; explain what the result says about sharing.
Common mistakes
- Assigning the collaborator to a bare local name,
sender = sender, in__init__: the instance never getsself.sender, so the first delegation inplace_orderraisesAttributeError. - Delegating without a defined requirement:
self.sender.send(...)fails at call time when the collaborator only hasnotify, because nothing at construction checked the method existed. - Exposing the collaborator as a plain attribute: any caller can replace
service.sendermid-flight with an object that does not satisfy the contract, and the failure surfaces later, far from the swap. - Subclassing only to reuse one method: inheriting from
EmailSenderexposes the whole sender interface on the service and hides the has-a relationship the design actually wants.
Practice: Easy
- Run the worked example and print
service.senderandservice.sender is sender; explain what the two objects own and what they share. - Build a second service with a
LogSenderwhosesendappends toself.messages; compare the outputs and state whatOrderServiceknew about the change. - Call
OrderService(None).place_order("A-100")and record theAttributeError; name the attribute that was missing.
Practice: Medium
- Add a check in
__init__that raisesTypeErrorwhen the collaborator has no callablesend; decide whether that check belongs in the constructor or inplace_orderand defend the choice. - Make
OrderServicehold two collaborators, anEmailSenderand aLogSender; explain how the delegation seam makes the second one additive. - Rewrite the example so
OrderServiceinherits fromEmailSender; list which calls keep working and which become misleading, then return to composition and justify it.
Practice: Hard
- Design a
ReportServicethat holds anExportercollaborator withexport(rows)and aFormatterwithformat(row); define who validates whom, and write tests with a fake exporter before implementing. - Build a failure lab: a collaborator that lacks the method, a collaborator swapped after construction, and a wrapper that forgets to store the collaborator. Show the exact error for each and name the mechanism.
- Connect this lesson to the inheritance lessons: take a hierarchy you built earlier and replace its deepest branch with a held collaborator, then list what disappeared from the public interface and what new seams appeared.
Lesson checklist
- I can say which object owns the sending behavior in the example and how the service reaches it.
- I can explain why replacing
EmailSenderwith a fake needs no change toOrderService. - I can name the seam between policy (
place_order) and mechanism (send). - I can spot the difference between holding a collaborator and inheriting from it in a small design.
Remember
Composition holds the behavior a class needs as a collaborator, and delegation forwards operations across that seam, so `OrderService` owns a sender instead of being one. The design pays off at replacement time: any object with a compatible `send` works, which makes fakes and second collaborators additive, while inheritance would have exposed the whole sender surface on the service.
Interview angles
What is the main purpose of **Has-a relationships**?+
A has-a relationship means an object owns or collaborates with another object rather than being a subtype of it. This is the core idea behind composition.
What should you pay attention to when using **Composition vs inheritance**?+
Composition makes an object hold the behavior it needs as a collaborator; inheritance makes the object a subtype that receives the behavior through lookup. An OrderService that holds a sender can swap senders and exposes only place_order, while a subclass would expose the sender's whole interface and freeze one family of senders into the class tree. Prefer composition when the relationship is has-a and replacement or testing matters; keep inheritance for genuine is-a contracts with shared method shapes.
How does **Delegating behavior** fit into this lesson?+
Delegation forwards an operation to a collaborator that owns the relevant behavior. The wrapper can add policy while keeping the specialized implementation separate.
Why is assigning `sender = sender` in `__init__` a bug in `OrderService`?+
The assignment binds a local name that disappears when __init__ returns, so the instance never gets a self.sender attribute and place_order raises AttributeError on its first delegation. The fix is self.sender = sender, which stores the collaborator on the instance for later calls.