Constructor overloadsĀ are fairly common in Swift codebases, but these could lead to the Bastard Injection anti-pattern. A common scenario is when we have a constructor that lets us inject a Test Double, but it also has a default parameter in the constructor:
class TodosService {
let repository: TodosRepository
init(repository: TodosRepository = SqlLiteTodosRepository()) {
self.repository = repository
}
}
The biggest problem here is when the default implementation is a Foreign dependency, which is a class defined using another module; this creates a strong relationship between the two modules, making it impossible to reuse the class without including the dependent module too.
The reason someone is tempted to write a default implementation it is pretty obvious sinceĀ it is an easy way to instantiate the class just with TodoService() without the need of Composition Root or something similar. However, this nullifies the benefits of DI and it should be avoided removing the default implementation and injecting the dependency.