Supposing I have an interface Foo and a given implementation FooImpl.
public class FooImpl implements Foo
If I want to define a new operation on this class that depends on the particular implementation, is it correct to define it in the implementation class or as a static method on an Util class like FooUtils.operation?
public class FooImpl {
public void operation() {
...
}
}
public class FooUtils {
public static void operation(Foo f) {
...
}
}
The first option forces me to cast to the given implementation class whenever I want to use it on an object that is declared of the type of the interface (it is good practice to program against interfaces). For example:
Foo f = FooImpl.newInstance();
((FooImpl) f).operation();
which is a bit ugly.
The second option doesn't have this problem but it is not very pretty either:
FooUtils.operation(f)
Best Answer
If not every implementer of
Foo
is supposed to containoperation()
, thenoperation()
cannot be declared inFoo
, plain and simple.Programming against interfaces rather than concrete classes is a good idea, but only if the interface actually is sufficient for your needs. If you need to call
operation()
, then you should declareFooImpl
, or maybe a custom subinterface ofFoo
, but neverFoo
. That would completely subvert the point of using an interface: not having to know concrete subclasses.