Friday 31 July 2015

Loosely Coupled Principle

Strive for loosely coupled design between objects that interact. (minimal interdependency on other objects)





Loose coupling is an approach to interconnect the components in a system or network so that those components, also called elements, depend on each other to the least extent practicable. Coupling refers to the degree of direct knowledge that one element has of another.

The goal of a loose coupling architecture is to reduce the risk that a change made within one element will create unanticipated changes within other elements. Limiting interconnections can help isolate problems when things go wrong and simplify testing, maintenance and troubleshooting procedures.

-------------------

For example, the Observer pattern provides an object design where the subject(observable) and the observer are loosely coupled.

The only thing the subject knows about the observer is that it implements a certain interface. (the observer interface). it doesn't need to know the concrete class of the observer, what it does or anything else about it.

We can add new observers at any time, because the only thing the subject depends on is a list of objects that implement the observer interface, we can add new observers whenever we want. In face, we can replace any observer at run-time with another observer and the subject will keep purring along. Likewise, we can remove observers at any time.

We never need to modify the subject to add new types of observers. Lets say we have a new concrete class come along that needs to be an observer. We don't need to make any changes to the subject to accommodate the new class type, all we have to do is implement the observer interface in the new class and register as observer. The subject doesn't care; it will deliver notifications to any object that implements the Observer interface.

We can re-use subjects or observers independently of each other. If we have another use for a subject or an observer, we can easily reuse them because the two aren't tightly coupled.

Changes to either the subject or an observer will not affect the other. Because the two are loosely coupled, we are free to make changes to either, as long as the object still meet their obligations to implement the subject or observer interfaces.

Loosely coupled designs allow use to build flexible OO systems that can hand change because they minimize the inter-dependency between objects.

No comments:

Post a Comment