Search code examples
javasolid-principlessingle-responsibility-principle

What's variant better? SOLID - SRP and interfaces


What variant is better? SOLID - SRP or the one with the interface?

class Some {
    private final IValidator validator;
    public Some(IValidator validator) {
        this.validator = validator;
    }

    public void doSomething() {
        if (validator.validate(data));
            // do something
    }
}

OR

class Some {
    private final Validator validator = new Validator();

    public void doSomething() {
        if (validator.validate(data));
            // do something
    }
}

Validator is used once.


Solution

  • By writing Validator validator = new Validator() you are actually increasing the coupling of your code, which is definitely against SOLID.

    Like @Kris told in the comments, the best way is to use the interface instead of the actual implementation - this actually corresponds more with the polymorphism and already after it it is about SOLID.