Every class has an interfaceinterfaces either explicit :(implement some interface
or conforms to some protocol
) or implicit (features usable from the outside, hiding the internals).
- Interfaces may be explicit, like when classes implement some
interface
or conforms to someprotocol
; - Interfaces may be implicit: it's what a class defines top be visible from the outside and to be used by other class, hiding the internals.
You might for example read a lot of advices about the use ofusing interfaces in patterns in theor programming to interfaces which refer to implicit interfaces. One example is GoF, but: most of the code examples in that book are C++ code, sometimes with pure abstract classes (the C++ equivalent to interface
), often, just referring to an implicit class.
So don't get mislead by ambiguity of words: you always need to think about interfaces when creating classes. At least their implicit interface. The key is to see it as a black-box, i.e. think of it as if someone else could rewrite it and you wouldn't know its internals. ThisThis is not overenginering. It's just OOP.
You You would go for the extra effort of explicit interfaces in the following situations:
- You find out that a class in your design should be replaceable with equivalent classes.classes;
- You want to reuse implicit interfaces, or part of them, potentially withare to be reused, on objects of a broad family of potentially unrelated classes.classes;
- You wantdeliberate use of language support to force yourself toyou think in terms of abstraction, and use language support for this purpose.
If you start to get nervous or stuck aboutregarding the granularity of such an explicit interface, wondering if and howinterfaces and why you might need to segregate itif further segregation is needed, then you should take a deep breath, and just go on with a first version of your new interface. If you find out later that the interface should be split, and if neededyou can always refactor later.