Python exercise · about 5 minutes · free
Dependency Inversion: Depend on What, Not Which
An order service that creates its own SMTP client cannot be tested without sending real emails. Pass the dependencies in.
The Dependency Inversion Principle says high-level code should depend on abstractions, not on concrete classes. In practice: program to an interface and inject collaborators through the constructor. The service neither knows nor cares whether the repository is a database or a list in memory, which is exactly what makes testing with fakes easy. It is the heart of "composition over inheritance".
Prices, versions and service names last checked 2026-11-19. They change, so confirm on the official pages before you rely on them.
Your quest: Write
OrderService(repo, notifier) with place(order): call repo.save(order), then notifier.send("order " + order["id"] + " placed"), and return the saved order. If repo.save raises, do not notify and let the error propagate.Try it now Runs in your browser. No sign-in needed. Ctrl+Enter to run.
Hint
Store both collaborators in <code>__init__</code>. Call <code>save</code> first; the notify line only runs if it did not raise.Output appears here.