Should an interface method implemented by a class always use all parameters? By interface I do not necessarily mean actual interfaces
, these could be other (abstract) classes which are extended, too.
I sometimes find it hard to use all parameters in all implementations. However, that seems to me as bad design. It makes me think of the mantra perfection is achieved not when there is nothing more to add, but when there is nothing left to take away
.
This especially applies in situations where (partially) optional behavior - such as flags that were previously set on the object instance - is refactored into an approach that makes use of polymorphism.
In pseudo code:
interface ValueProcesser {
public Value doSomethingWithValue(value, parameter1, parameter2);
}
class Implementation1 implements ValueProcesser {
// Does nothing - no optional behavior applies in here.
public Value doSomethingWithValue(Value value, parameter1, parameter2) {
return value;
}
}
class Implementation2 implements ValueProcesser {
// Behavior that only uses the first parameter
public Value doSomethingWithValue(Value value, parameter1, parameter2) {
doSomethingWithValueUsingParameter1(value, parameter1);
return value;
}
}
class Implementation3 implements ValueProcesser {
public Value doSomethingWithValue(Value value, parameter1, parameter2) {
doSomethingWithValueUsingParameter1AndParameter2(value, parameter1, parameter2);
return value;
}
}
Now for client code with a ValueProcesser
instance, it is really easy to simply call:
public void main() {
ValueProcesser.doSomethingWithValue(value, parameter1, parameter2);
}
and everything will work. The question is, should the unused parameters be refactored away somehow and how can I refactor to get rid of their redundancy?
For the record, it does not make sense to set those parameters as members of the Implementation
classes.