Created
February 2, 2019 19:40
-
-
Save johnhammerlund/b6e135a356fedafe01073f30e89de282 to your computer and use it in GitHub Desktop.
Swift Dependency Injection - ELI5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// ❌ Without dependency injection | |
public final class Kid { | |
private let fridge = Refridgerator() | |
func eatLunch() { | |
let food = fridge.fetchFood() | |
let drink = fridge.fetchDrink() /// POTENTIAL ERROR: Might be expired! | |
consume([food, drink]) | |
} | |
private func consume(_ items: [Consumable]) {} | |
} | |
/// ✅ With dependency injection | |
protocol DrinkService { | |
func fetchDrink() | |
} | |
protocol FoodService { | |
func fetchFood() | |
} | |
public final class Kid { | |
private let foodService: FoodService | |
private let drinkService: DrinkService | |
init(foodService: FoodService, drinkService: DrinkService) { | |
self.foodService = foodService | |
self.drinkService = drinkService | |
} | |
func eatFood() { | |
/// Someone else will make sure you have something when you sit down to eat | |
let food = foodService.fetchFood() | |
let drink = drinkService.fetchDrink() | |
consume([food, drink]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment