Skip to main content
Tweeted twitter.com/#!/StackProgrammer/status/532817111651868672
edited tags
Link
gnat
  • 20.5k
  • 29
  • 117
  • 309
Source Link
dabd
  • 161
  • 5

Programming against interfaces in Java

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)