Javier Salinas bio photo

Javier Salinas

Software Engineer located in Barcelona, interested in Distributed Systems and simple designs using TDD.

Email Twitter Google+ LinkedIn Stackoverflow

Recently I was thinking about interface verbosity.

Currently I am working on a Spring Framework based project ( once again ;( ) and I am seeing a common coding pattern with which I disagree.

I would also like to recommend Uncle Bob’s post about “Interfaces Considered Harmful” which inspired me to write this post.

How many times have you seen a structure like this one?

 public interface SomeService {
     void someMethod();
     void anotherMethod();
 }

 public class SomeServiceImpl implements SomeService {
      public void someMethod() {
        ...
      }
      public void anotherMethod() {
        ...
      }
  }
 

Looking at the code, I think:

  1. Why the use of suffix “Impl”? (C# developers would use the prefix “I” for interfaces).
  2. Does the implementation really need an interface?

Regarding the first item: this naming pattern is used when the interface has the proper name and the developer can’t find a better one for the implementation.

Second item: this one is probably related to the Dependency Inversion Principle (DIP):

    A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
    B. Abstractions should not depend on details. Details should depend on abstractions.

Whenever it is hard to find a different interface/implementation name - this is hinting us that the interface only needs a single implementation.

In the old-style Spring flow pattern “Controller -> Service -> DAO” we often see one interface paired with its implementation for each Service and DAO. But actually in 95% of all scenarios only one interface implementation is required. (I am guessing it, don’t take this as a law)

So should we always create 2 objects when we build a component? I would say NO.

I agree that there are some services which could have multiple implementations like e.g:

 public interface PaymentService {
     void payAnInvoice();
 }

 public class StripePaymentService implements PaymentService {
      public void payAnInvoice() {
        ...
      }
  }

  public class PayPalPaymentService implements PaymentService {
        public void payAnInvoice() {
          ...
        }
    }

    ...
  

In such cases… it is great to use an interface and inject the interface as a dependency. But it does not apply to all components you need. (To be honest, only in rare cases you need an interface with multiple implementations)

Conclusion

I think that interfaces are great when you are developing an API; they act like contracts between systems; or when you need multiple implementations.

But I am sure that we should not use an interface for every component we create and, sadly, in the Spring eco-system interfaces are used abused much to often.