Subscribe to PHP Freaks RSS

Matthias Noback: When to add an interface to a class

syndicated from www.phpdeveloper.org on August 28, 2018

Matthias Noback has a tutorial posted to his site sharing his thoughts on when adding an interface to a class is useful. Here he's talking about using interfaces as a structure for your application, making it easier to understand and more structured.

I'm currently revising my book "Principles of Package Design". It covers lots of design principles, like the SOLID principles and the lesser known Package (or Component) Design Principles. When discussing these principles in the book, I regularly encourage the reader to add more interfaces to their classes, to make the overall design of the package or application more flexible. However, not every class needs an interface, and not every interface makes sense. I thought it would be useful to enumerate some good reasons for adding an interface to a class. At the end of this post I'll make sure to mention a few good reasons for not adding an interface too.

He then offers five suggestions of cases where an interface makes sense:

  • If not all public methods are meant to be used by regular clients
  • If the class uses I/O
  • If the class depends on third-party code
  • If you want to introduce an abstraction for multiple specific things
  • If you foresee that the user wants to replace part of the object hierarchy

For each item in the list he provides a summary of the suggestion and some code snippets to back it up. He ends the post with a recommendation about how to handle most other situations where you think an interface might be useful: use a "final" class instead.