Search code examples
oopdesign-patternscoding-stylesolid-principles

Is it good practice for every public method to be covered by an interface?


It's good practice for a class' implementation to be defined by interfaces. If a class has any public methods that aren't covered by any interfaces then they have the potential to leak their implementation.

E.g. if class Foo has methods bar() and baz() but only bar() is covered by an interface then any use of baz() doesn't use an interface.

It feels like to get cleaner code it would make sense to either:

  • create extra interfaces if the class has to have those methods (eg a separate interface to cover the behavior of baz() above)
  • or ideally refactor (eg using more composition) so the class doesn't need to have so many methods (put baz() in another class)

Having methods not covered by an interface feels like a code smell. Or am I being unrealistic?


Solution

  • I consider it as "overusing" the interface.

    Interface can give you access only to limited functionality, therefore it is good for gathering more classes with similar functionality into one List<Interface> and using them, for example.

    Or if you want to keep loose coupling principle, you rather give another component some interface than the whole class(es).

    Also some classes should have restricted access to another classes, which can be done with interfaces too.

    However high cohesion principle (which is usually connected to loose coupling) does not prevent you from using class itself, if two classes are and should be "strong" connected to each other.