Programming facing the interface and not the implementation, why?

Asked

Viewed 5,474 times

64

What are the main reasons (in practice) that lead developers to apply the practice of developing for interface and not for implementation?

1 answer

54


Because interfaces are only contracts of what the object has or is able to do. So you can use any object as long as the contract is guaranteed.

Having only the contract you can get better:

  • Maintainability - changes become more isolated, do not need to change everything that accepted one concrete class to accept another needed. Certain details are no longer important and it is possible to change the implementation without breaking the application.
  • Extensibility - Allows new implementations to be made without altering everything expected by a given object, so certain behaviors become more generic and can manipulate objects that it does not know since it contains the expected contract.
  • Testability - it’s easy to replace a real production object with a fake that facilitates testing.

With the interface is one of the possible ways to reduce the coupling.

It helps in encapsulation and abstraction which is more than having some private members. Prioritizing the use of the interface the code clearly only says what it needs there and the languages usually prevent access to other members not present in the declared interface even if you know that these members exist in the object.

In some cases using interface is the same as using abstract classes.

There’s an answer which shows in practice how important it is to be as generic as possible in the type of object you want and as specific as possible in what you want to do with this object, when you use the interface, and it is set correctly, you are saying that you will only do something there that the interface allows, even if the object as a whole allows more.

This facilitates several design standards, especially the dependency injection and control inversion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.