Suppose I'd like to implement the templating pattern, but the only real differences between the subclasses are their choices of some invariant dependencies.
Is there a drawback to preferring this style:
public abstract class AbstractClass {
private final DependencyA dependencyA;
private final DependencyB dependencyB;
public AbstractClass(final DependencyA dependencyA, final DependencyB dependencyB) {
this.dependencyA = dependencyA;
this.dependencyB = dependencyB;
}
public void doStuffWithDeps() {
//Business logic using the dependency fields
}
}
To this style?
public abstract class AbstractClass {
protected abstract DependencyA getDependencyA();
protected abstract DependencyB getDependencyB();
public void doStuffWithDeps() {
//Business logic using the dependency getters
}
}
I don't have much experience using the first of the two, but I'd argue that in cases where the dependencies don't change over time, the first is preferred as there is no reason to keep asking for the dependencies for each call to the doStuffWithDeps()
method. However, whenever I've seen this kind of problem it has always been solved with the second implementation, which makes me wonder if I've missed something.
I realise inheritance is not really a good solution to these kinds of problems in the first place, but suppose these are my two options, which one should I prefer and why?