Junior — Middle
What are the advantages and disadvantages of using a constructor when implementing dependencies in code?
sobes.tech AI
Answer from AI
Advantages of constructor-based dependency injection:
- Explicit declaration of dependencies — all necessary objects are passed through constructor parameters, improving readability and testability.
- Ensuring immutability — dependencies can be made final, increasing reliability.
- Simplifying testing — mock objects can be easily substituted during unit tests.
Disadvantages:
- With a large number of dependencies, the constructor can become cumbersome.
- Not always convenient if dependencies are optional or need to be created lazily.
Example:
public class Service {
private final Repository repository;
public Service(Repository repository) {
this.repository = repository;
}
public void doWork() {
repository.saveData();
}
}
Thus, the constructor provides explicit and reliable dependency injection, which promotes clean architecture.