Repaso
Español
Design & PracticesIntermediateDP-05

Dependency Inversion means…

Options

  1. Subclasses call the methods of their parent classes in reverse
  2. High-level modules depend on abstractions, not on concrete details (Correct option)
  3. Dependencies are installed in the reverse order of their use
  4. Inheritance is used in place of composition in every class

Answer

High-level modules depend on abstractions, not on concrete low-level modules

Why

High-level code (business rules, like OrderService) should not depend directly on low-level details (like the Stripe library). Both should depend on an abstraction, e.g. a PaymentGateway interface.

Then you can swap Stripe for PayPal, or for a fake in tests, without touching OrderService.

class OrderService:
    def __init__(self, gateway: PaymentGateway):   # abstraction
        self.gateway = gateway

service = OrderService(StripeGateway())   # concrete choice at the edge

Remember

Depend on interfaces, plug in the concrete class from outside.

Key terms

Practice this question in Repaso