Prefer dependency injection to hardwiring resources

The classes that are dependent on the underlying resources are good candidates for dependency injection. Let say we have a DatabaseManager class that is dependent on database config. In this case, dependency injection is the most flexible and multiple clients will be able to use it. See the code segment below:

public class DatabaseManager {
    private final DatabaseConfig config;

    public DatabaseManager(DatabaseConfig config) {
        this.config = Objects.requireNonNull(config);
    }
}

It would be inappropriate and inflexible if we:

  • Implement this as a static utility
  • Implement this as a singleton

The reason:

Static utility and singleton are inappropriate for classes whose behavior is parameterized by other resources.

More about more prefer dependency injection to hardwiring resources

  • Prefer dependency injection to hardwiring resources
  • Not every class needs to be singleton or noninstantiable. sometimes classes behavior is parameterized by underlying resources. In these cases, we need to pass the resource to the class
  • One common way of doing this is passing the resource through constructor when creating a new instance
  • DI provides flexibility and testability
  • In big projects w/ lots of dependencies, handling this can be a bit problematic. In this case, dependency injection frameworks can be used to eliminate the clutter
Share