Course contentsShow
← Software Engineering
Lesson 223 of 1,9336. SOLID PrinciplesFree lesson

Inverting Dependencies with Interfaces

Using interfaces and abstract classes to reverse the direction of source code dependencies.

Inverting Dependencies with Interfaces

You'll learn: How to use interfaces and abstract classes to flip the direction of dependencies, making high-level code independent of low-level details.

The Core Problem

Normally, high-level code (like your business logic) depends directly on low-level code (like database access or file systems). This creates a rigid structure where changes to low-level details force changes to high-level code. We need to reverse this flow.

How Interfaces Invert Dependencies

Think of an interface as a contract written by the high-level code, defining what it needs without caring how it's provided. The low-level code then implements this contract.

Before inversion: Your ReportGenerator class directly depends on a MySQLDatabase class. If you switch to PostgreSQL, you must change ReportGenerator.

After inversion: ReportGenerator depends on an IDatabase interface it defines. Both MySQLDatabase and PostgresDatabase implement this interface. Now ReportGenerator doesn't know or care which database you use—the dependency arrow has been reversed.

The Reversal in Action

Without inversion, dependency arrows point downward: BusinessLogic → DatabaseCode.

With inversion, both point toward an abstraction in between: BusinessLogic → IDatabase ← DatabaseCode.

The high-level module (BusinessLogic) now controls the interface definition. The low-level module (DatabaseCode) must conform to it. The source code dependency has been inverted—low-level details depend on high-level abstractions, not the other way around.

Why This Matters

You can now swap implementations without touching business logic. You can test business logic with mock implementations. Your architecture becomes stable, flexible, and change-resistant at the core.

Key Takeaway: Dependency inversion uses interfaces or abstract classes as a boundary, forcing low-level details to depend on abstractions defined by high-level policy, reversing the natural dependency direction.