Dependency Inversion Principle (DIP)

Verze:

02. 07. 2025

Zodpovědná osoba:

Dominik Šlechta

Rule

High-level modules should not depend on low-level modules; both should depend on abstractions (e.g., interfaces or abstract classes).

Description

The Dependency Inversion Principle (DIP) advocates for decoupling high-level modules from low-level ones. Both should depend on abstractions, which makes the code more flexible and easier to maintain. This allows for better testability, as dependencies can be injected or mocked, and promotes loose coupling between components.

Benefits

  • Loose Coupling: Reduces the dependency between high-level and low-level modules.

  • Improves Testability: Dependencies can be injected or mocked, facilitating unit testing.

  • Promotes Flexibility: Changes in low-level modules won't impact high-level modules if they both rely on abstractions.

Example (Correct):

interface PaymentGateway {
    public function processPayment($amount);
}

class CreditCardPayment implements PaymentGateway {
    public function processPayment($amount) {
        // Credit card payment logic
    }
}

class OrderProcessor {
    private $paymentGateway;

    public function __construct(PaymentGateway $paymentGateway) {
        $this->paymentGateway = $paymentGateway;
    }

    public function processOrder($amount) {
        $this->paymentGateway->processPayment($amount);
    }
}

Example (Incorrect):

class OrderProcessor {
    private $creditCardPayment;

    public function __construct() {
        $this->creditCardPayment = new CreditCardPayment();
    }

    public function processOrder($amount) {
        $this->creditCardPayment->processPayment($amount);
    }
}