3

Suppose I have distinct classes that have the same behavior, which can be represented like this:

public interface Behavior {
    void operationA();
}

public class ImplementerA implements Behavior {
    public void operationA() {

    }
}

public class ImplementerB implements Behavior {
    public void operationA() {

    }
}

But ImplementerA and ImplementerB are used by distinct clients; ClientA only uses ImplementerA and ClientB only use ImplementerB; other than these, there are no other clients for ImplementerA and ImplementerB.

In this scenario, does the interface Behavior have any purpose? Should it be created because maybe future requirements changes...

  • 4
    If I use ImplementerB in ClientA, will it break? – Phoshi Jul 15 '14 at 12:58
  • Prefer composition to inheritance... unless a class is used polymorphic. – BЈовић Jul 15 '14 at 13:15
  • @Phoshi Functionally, yes. – m3th0dman Jul 15 '14 at 14:03
  • 2
    @m3th0dman: Then this is a clear misuse of polymorphism. – Phoshi Jul 15 '14 at 14:07
  • 1
    @m3th0dman: Interfaces are giving you polymorphic behaviour whether you like it or not. If new ClientA(new ImplementationB()) is valid code that works, and yet breaks at runtime, then you have polymorphism, and it is being misused. Interfaces are not just categorising, they are abstracting over behaviour. – Phoshi Jul 16 '14 at 8:10
2

If you're using a language where classes must be hard-coded into the code (e.g. Java/C#) then it might make sense to use an interface in case you ever want to change the implementation of Behavior that gets passed to ClientA or ClientB without recompiling. This usually happens when you want to unit test some code by providing mock implementations of Behavior. Without an interface you'd have to change the import statement of the client code so that it references the right implementation and recompile it.

In languages that don't hard-code references to classes using globally-unique identifiers (which is what fully-qualified names such as com.yoursite.Foo are) this isn't an issue and there's no need to make an interface. However languages with this kind of module system are relatively unpopular functional languages (e.g. Standard ML, OCaml) so it likely doesn't apply to you.

Note, however, that not every class can be implemented as an interface. Consider:

public class LooksAtOthers {
    public LooksAtOthers binaryOperation(LooksAtOthers other) {
        ...
    }
}

The binary operation here looks at the private fields of other. This comes up a lot when implementing data structures; in order to do efficient merges or unions you have to be able to look at the implementation of both operands. This can't be done from an interface:

public interface CantLook {
    CantLook binaryOperation(CantLook other)
}

public class CantLookImpl implements CantLook {
    public CantLook binaryOperation(CantLook other) {
        // no idea what type CantLook has
    }
}

Here CantLook is an interface, so the class implementing CantLook has no idea what private fields other has. As a result if binaryOperation required looking inside other, it can't be implemented efficiently any more.

Note also that using a class makes debugging somewhat easier. With a class any given client code only interacts with one implementation; it either works or it doesn't. With an interface there can be any number of implementations and nothing stops someone from making a bad one. If you use an interface and ClientA breaks, you have to look at which implementation of Behavior broke it. Someone might've created and passed in a buggy ImplementerC.

So the bottom line is: it depends. Does it bother you to have to change import statements? Are you doing unit testing? Do you need to look at other instances of the class?

  • For your example, using generic typing you can have an interface public interface A<T> and then the class public class Aimpl implements A<Aimpl>, inside Aimpl you can have the binary operation. – InformedA Jul 15 '14 at 13:39
  • @randomA You still can't call binaryOperation on an A<T1> and a A<T2> where T1 != T2, and you'd have a dependency on the implementing class. In other words, it's not much better than depending on Aimpl directly. – Doval Jul 15 '14 at 14:02
  • then simply put, your binary operation method signature should be public IBinaryOperand binaryOperation(IBinaryOperand operand) where IBinaryOperand would be another interface – InformedA Jul 15 '14 at 14:30
  • @randomA You won't be able to implement binaryOperation that way. An argument of type IBinaryOperand doesn't allow you to inspect its private fields, which we've established is a necessity for binaryOperation. There's no way around the issue; if you wish to inspect two instances of a class you must know that both operands have the same class. This means the client code must also know they have the same class, since the client code is providing the operands. That's part of the trade-offs between classes and interfaces. – Doval Jul 15 '14 at 14:33
  • once you have the interface you can upcast inside the method and then do just as you want. I can think of a few ways that seem hacky to achieve what you say as well. I think in all cases, that is ok because exposing the actual class would be the biggest hack of them all. – InformedA Jul 15 '14 at 14:38
2

The main reason to use interfaces is explained in the dependency inversion principle ( the D in SOLID ).

  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Abstractions should not depend on details. Details should depend on abstractions(***).

The goal of this is decoupling the higher level from specific implementations, allowing for more maintainability.

Maintainability's main issue is compensate the unability of human beings to foresee the future.

Statements like "ClientA only uses ImplementerA and ClientB only use ImplementerB" has proven to not hold true forever.

*** NOTE: In the context of SOLID and OOD, "abstration" means than it cannot be instantiated, like an abstract class or interface.

Something that cannot be instantiated needs to have very little reason to change overtime. That way code that depends on abstractions depend on things that are stable ( the what vs the how ). Code that depends on abstractions have less reason to change that code that depends on concretions.

  • 1
    This goes against popular opinion but the "both should depend on abstractions" part of the principle is flawed because classes are abstractions. In particular, they're abstract data types, one of the [two fundamental kinds of data abstraction])cs.utexas.edu/~wcook/Drafts/2009/essay.pdf) (the other being interfaces). The fact that the implementation of a class can't be swapped easily in mainstream OOP languages is an arbitrary design decision; there are languages where you can change implementations freely. – Doval Jul 15 '14 at 14:24
  • @Doval in the context of SOLID abstract means that cannot be instantiated. I'll add it to the answer. – Tulains Córdova Jul 15 '14 at 14:45
  • 1
    And how does an inability to instantiate code help in any way? – Doval Jul 15 '14 at 14:47
  • 1
    @user61852 So should you add interfaces to every (let's say non-trivial) class then? – m3th0dman Jul 15 '14 at 19:44
  • 1
    @m3th0dman The other way around. You design first and implement later. So you don't add interfaces to classes. You design interfaces. Then you write classes that implement those interfaces. – Tulains Córdova Jul 15 '14 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.