Junior — Middle
Why is the constructor used when injecting dependencies into an object?
sobes.tech AI
Answer from AI
Dependency injection through the constructor provides several important advantages:
- Immutability of the object: All dependencies are passed during object creation, allowing fields to be final and ensuring the object is fully initialized.
- Explicit dependencies: The constructor clearly shows which components the class depends on, improving code readability and maintainability.
- Simplified testing: Mocks or stubs can be easily substituted during testing by passing them into the constructor.
- No state after creation: The object cannot end up in an inconsistent state since all dependencies are set immediately.
Example:
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void registerUser(User user) {
userRepository.save(user);
}
}
Here, UserService explicitly requires UserRepository through the constructor, making the dependency transparent and mandatory.