Dependency Inversion with Protocol Abstractions
Depending on abstractions not concretions using Swift protocols as boundaries.
Dependency Inversion Principle
High-level modules should not depend on low-level modules. Both should depend on abstractions (protocols).
// WITHOUT DIP:
class OrderService { let db = SQLiteDatabase() } // depends on concrete
// WITH DIP:
class OrderService { let db: Database } // depends on abstractionDefining the Abstraction
Extract a protocol that captures the contract your high-level module needs.
protocol Database {
func save<T: Encodable>(_ value: T, key: String) throws
func load<T: Decodable>(key: String) throws -> T
}All lessons in this course
- Layers: Domain, Data and Presentation
- Use Case and Repository Patterns
- Dependency Inversion with Protocol Abstractions
- Wiring Layers Together without a DI Framework