Hello! Welcome back for another post!

Today, we’ll discuss what loose coupling is and why you should aim for it.

What is it?

Loose coupling is a ‘good software engineering principle’ that asks you to keep the level of knowledge your components have about each other to a minimum. Components that interact with each other should know as little about each other as possible.

Why should I care?

This allows you to make changes to one component without affecting the other. In other words, you can indepedently work on each component without considering the others.

Let’s learn from a negative example. If class B inherits from class A, then class B is tightly coupled with class A. If you change class A, that will affect class B (because B inherits data/behavior from A). In other words, you cannot work on A without effecting B. In yet other words, you cannot work on your components independently.

How do I achieve it?

Clearly, inheritance is not loose coupling.

Instead, consider if class B has an instance of class A. In other words, we use composition. Now, as long as class B doesn’t access the internals of class A, we have achieved much looser coupling. We can make changes to each of these without affecting the other.

We can do one step better. B should have an instance of an interface that A implements. This is even looser coupling because B has even less knowledge of A, it doesn’t even know that A exists (how sad, but useful)!

Being the smart-asses that you are, you may be saying “Ok, but now B is coupled with the interface!”

Gah-uh-uh, just hear me out for a second! Yes, B is now coupled with an interface, but interfaces change much less frequently than implementations, so it is ok to be coupled with an interface.

Can you give me a summary?

Sure thing, lazy one.

  • loose coupling is a good software engineering principle that asks you to keep the level of knowledge your components have about each other to a minimum.
  • Inheritance is not loose coupling (changes in base class affects all derived classes).
  • Composition is looser coupling (changes in composite/composee don’t affect each other, assuming you don’t access internals/privates!).
  • Composition with interfaces is even better! Now, you are coupled with an interface instead of an actual implementation. It is ok to be coupled with an interface because they change infrequently.

Thanks for stopping by and have an amazing day!