Loosely coupled classes gives flexibility. If I understand it right, Event flow, Observer Pattern and Design Patterns like MVC focus on loose coupling. So in this context I am aiming towards making a project where all the classes are loosely coupled.
So, for example I have a class A that uses B:
then instead of a.b.doThis() ;
I will be going like this :
b.addEventListener( B.OnEventHappens, doThisInA ) ;
So, my question is. If this sort of loosely coupled relationship throughout a project is a good thing to do? Would it make a robust project? Or is it not advisable to use it on the “Extreme” side?
1
There are many kinds of coupling other than those you have described. Anything that makes one piece of code change because another has changed is coupling. All coupling can’t be avoided because you will need to have different bits of code work together.
Coupling isn’t the only concern you have anyway, so there are tradeoffs. For example, using the Observer pattern makes the code hard to read or statically analyze, because there isn’t a reasonable way to tell who is actually doing the observing.
If there were any practice that was clearly always the best choice in all circumstances you would basically never see it done any other way.
There is a balance that needs to be achieved between looseness of coupling and complexity. As the person responsible for the overall architecture, you need to strike that balance.
When we call a ToString()
method on an object, we can do so safely because we know all of our classes derive from a base class that has a ToString()
method, and that method can be overridden in derived classes to achieve better output. Do we add event listeners to ToString()
? No, we don’t. Why not? Because it would add additional complexity for no additional benefit.
Do we add event listeners to actions which may or may not have a corresponding target to receive the action? Of course. Why? Because it generalizes our class model, and allows optional message passing where it is appropriate.
If you have two classes that will always work together, but whose methods will never talk to any other class (at least within the realm of their respective Interfaces), you would not decouple them with events. Why? Because decoupling doesn’t make any sense in that context. Decoupling can actually make things more difficult, because there are situations where one class must have knowledge of the other class’s state in order to function properly (in other words, they must coordinate their efforts). Decoupling makes classes know less about each other, not more.
1