Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should we place interfaces with classes that use them rather than those that implement them?

I was going through an article by Robert C. Martin and at one place he gave a example like this:

The first image shows that there's a cyclic dependency between the two packages. To remove this dependency a new interface is added in the second image. B implements the interface and Y uses it. And Martin makes the following point:

Interfaces are very often included in the package that uses them, rather than in the package that implements them.

My question is, why should we arrange interfaces this way? What is the reasoning behind packaging interfaces this way? According to Common Closure Principle classes that change together should stay together. Is an interface closer to its implementer or its user, in terms of change???

enter image description here

like image 851
Sidharth Panwar Avatar asked Apr 30 '11 07:04

Sidharth Panwar


1 Answers

Technically, the user is no closer to the interface than the implementor. In terms of change both will need to change when the interface changes.

However, why would the interface change?

The user calls to an interface so it can be independent of whatever implementor is available. Therefore the definition of the interface is dictated by the needs of the user.

As the user dictates the definition of the interface, there is no point changing the interface if the user doesn't need it. An implementor requiring a change to the interface to accommodate the implementation should send up red flags. Why does it need more or different information from the user? What use is that to the user?

Also, the implementor "merely" depends on the interface in as much as it needs to provide implementations for each of the methods in the interface. But it is free to provide empty stubs, in essence delivering a NOP to its clients.

So, the user's needs drive changes to the interface and changes to the interface drive changes to the implementor(s). As such the user is functionally much closer to the interface than the implementor. Which makes a good case to declare the interface with the user and not the implementor.

like image 175
Marjan Venema Avatar answered Sep 20 '22 08:09

Marjan Venema