Do I Need That Interface?

In software development we are told early on that you should "Program to the interface, not the implementation". This is great advice when you are programming against remote systems, or services that you don't control. However, it seems like what most developers hear is "Every class should have a corresponding interface".

We end up creating interfaces like IPrettySweetClass, with the single corresponding implementation: PrettySweetClass. The problem is that the IPrettySweetClass interface was probably written in a way that only allows one implementation. It is either so specific that others can't fully implement it themselves or it wouldn't make sense to have two implementations in a code base at a single time. Code-bases quickly become riddled with IThis & IThat interfaces which are offering no real value to anyone other than allowing a developer to check the "I programmed to the interface, not the implementation" option on their "best practices" checklist.

The easy solution to this problem is to ask some pretty simple questions before deciding to create an interface.

  • Is there a current need for more than one different implementation of this functionality?
  • Will this interface outline a single responsibility or concept?
  • Can a clear & descriptive interface name be identified by the behaviors it will outline?
  • Is the primary utilization of this functionality going to happen outside of the codebase that defined it?

Note: There is no "one size fits all" answer to determine if an interface is needed but, the goal of this is to get you thinking before creating interfaces that you don't need.

If you cannot answer a definite "yes" to at least one of these questions, you do not need that interface. Even if you did answer yes to one of them, that's great but, there is still one big question you need to answer.

Is there clearly defined criteria for using one implementation over another?

This question isn't optional. If you cannot answer this question with "yes" you have bigger problems than "Should I create an interface?". Failure to answer this question means that you do not fully understand what problem you are trying to solve. You need to stop writing code & find a way to answer this question.

Creating interfaces without a clear definition about when you should use one implementation over another is going to do nothing but cause confusion for people seeing that interface. And if I had to guess, the entire codebase that defined that interface is a confusing mess that no one can understand.