the purpose of interfaces

Definition: Do not depend on things that you do not need.

Two problems of not using Interfaces:

  1. Tight coupling between modules.
  2. Possibility of OCP and SRP violation.

Let’s look at an example. With Switch and Light design.

First case: Without the use of interfaces.

Here, the switch is tightly coupled with Light module. But what if the switch should also used for interacting with Fan and other appliances. For this we can:

  1. Add case statement => This will violate SRP
  2. Change the Switch code to point to Fan => OCP violation.

And one more thing: If we make changes in Light module or any other module that Switch interacts, then the Switch module also has to recompile.

We can come up with a better solution for this scenario.

This way, if new appliances come in, we can inherit them from interface. This way we can prevent violation of OCP, SRP.

==Coming to the coupling:==

By mistake, since Appliances are inherited from the Interface, we tend to believe the bond between interface and Light is the tightest.

But counter intuitively, the bond between switch and interface is the tightest As without interface Switch does not work or do its functionality.

So it is better to keep the interface in the same module as Switch and naming convention can also give priority to the bond between Switch and Interface, rather than Interface and Light.