Some people say that interfaces are useless. Actually, I hear it in my current job (a lot). Some of my teammates kind of hate interfaces… I’m not joking. Whenever they see interfaces in my code, some of them start summoning a battery of arguments against them… they think interfaces are useless or unnecessary.

I don’t believe that, but I won’t deny that some of their arguments are interesting. I will try to introduce some of them, and then I will try to explain the reason why I don’t think interfaces are useless and, even more, they are very important.

TL;DR

IMHO, this is what you should do with interfaces:

  • If you have several classes working in a similar way, use interfaces to create a standard behavior. This way you will get immediately knowledge about what every implementation is able to do.
  • If you need more arguments and your contract doesn’t support them, move away from the singletons and start using stateful prototype scoped objects.
  • If a class contains core business logic and it could be the only implementation of an interface, don’t use an interface and just create the concrete class.
  • If the class contains logic about details (persistence, REST calls, UI, etc) use an interface and implement it on a more “external” layer.
  • Read about the Dependency Rule and Dependency Inversion Principle (the “D” of S.O.L.I.D. design principles). If you can, _Clean Architecture _from Robert C. Martin is a must-read.

Arguments against the use of interfaces

You won’t use it in a polymorphic way!

Suppose that we make a REST call to an external system and it gives us a flat Customer in JSON format, then we want to transform that Customer into one of our own model.

Then, we create a Transformer interface with one method transform that receives a Data Transfer Object (DTO) and returns a Model Object.

#java #software-architecture #software-engineering #object-oriented-design #interfaces

Why and When Are Interfaces Useful?
1.45 GEEK