Spies and revolutionaries are often organized into small groups called cells. They might know the people in the same cell, but not from other cells. This ensures that when one cell is discovered, details about other cells will remain protected. This principle can be applied to coding as well. We can organize our code into modules and limit the interactions between them. If one module got replaced or compromised, other modules should continue to work.
Minimize Coupling
Modules knowing each other is not as paranoid as spies or revolutionaries! But we should be careful about how many modules we interact with and how we came to interact with them.
Imagine that we are building a house. We hire a General Contractor to get the work done. The contractor may or may not do the construction personally. He can hire a number of subcontractors, split the work and assign to them. As clients, we don’t need to interact with these subcontractors. All the headaches related to these subcontractors are isolated from the clients.
Similarly, while writing modules, instead of having one module which depends on many other classes, we can have a hierarchy of classes. In this case, each class need to be concerned about only one other class. This makes it easier when a change happens to some class. We need to modify only the class which uses this changed class and not the entire module. This also helps reduce the dependencies among classes.
Systems with many unnecessary dependencies are very hard to maintain, and they are highly unstable.
- summary of Decoupling and the Law of Demeter, from The Pragmatic Programmer: From Journeyman to Master
No comments:
Post a Comment