To some it seems like every class needs to implement an interface.  But this is over-engineering and makes simple solutions unnecessarily complex.

Interfaces do help in strongly typed languages like Java by defining the contract between classes or packages, but the real functionality of software should not be obscured by their presence.

An interface isn't always a positive addition.  It is an indirection, an abstraction away from the real implementation of a method. This makes software more complex and slows development, especially where projects use Spring to wire together classes in XML so the concrete implementation is hard to find. It's also an additional file to manage which adds a small overhead through code bloat.

Often an interface is written before the coding approach has been decided, meaning multiple source files need refactoring.

It's common nowadays to create an interface to allow simple mocking of a service, especially in the Spring framework with libraries like EasyMock. But a mocked service that is driven by XML doesn't refactor easily. A traditional subclass might be slightly more effort but it can handle complex logic readily, overriding only the methods that are needed for the simulation.

Try to develop the concrete class and split out the abstract interface at the latest possible time when it is clearly needed.  

Ask yourself:

  • Have I used an interface when a base class might have done the job just as well?

  • Have I used an interface to cater for some future scenario that isn't even on the horizon?

  • Can I use a simple class for now and change it into an interface later?

  • Is the interface class in the right package? Normally all related interfaces are in one package.

String could easily have been designed as an interface, but sanity prevailed and it was kept as a concrete class for simplicity.  Often a plain old Java class is sufficient.

Tip: Always start with a plain old Java class with methods that can be overridden*.  Then, at a future time when it becomes clear an interface is absolutely required, extract the methods of the base class out into an interface.  Only one implementing class is a good indicator that perhaps the interface is unnecessary code bloat.  *unless you are writing an API, which most are not.

blog comments powered by Disqus