Decoupling and cohesion are phrases that are thrown around in software very often. You kind of know what they mean, but do you really?
Decoupling
Coupling in software architecture usually applies to modules in OOP. It measures how dependent are modules from each other - how strong is the connection between them. Why should that bother us? The main problem is that if modules are highly coupled, that usually means that when you change something somewhere, you create a ripple effect and you have to change other modules as well.
How do we measure it? There's no one rule, but there are some guidelines.
- If a change in class A forces you to change other modules, it's a sign that these modules may be highly coupled
- If you use some custom classes, instead of primitives to pass data around modules, you increase the strength of the relationship
- If module B has a pointer to object A, and vice versa
- Think of your modules as independent, as if the rest of the program didn't exist
- Prefer abstractions - they tend to help you think of your modules as independent
- Design patterns of course
- Cohesive code is often decoupled
- Prefer composition, over inheritance.
- Use layers of architecture
Interfaces != Decoupling
You can have decoupled code, without using one interface.
Cohesion
Cohesion is strongly connected to decoupling but there is a subtle difference.
"In computer programming, cohesion refers to the degree to which the elements of a module belong together."
If you have low cohesive code, it's almost definitely strongly coupled. SOLID's Single Responsiblity Rule commands to created modules, with single responsibility, hence cohesive.
Your module is cohesive, if:
Your module is cohesive, if:
- The functionalites of the class have a lot in common and the class' responsibility can be described in a simple sentence without "and", "or".
- Doesn't use unrelated dependencies (network module using database module)