Coupling, simplified
When an object calls a method, property, etc. of another object we say the objects are coupled. We call it coupling because now the callee cannot change anything about its own method/prop. w.out breaking the caller.
Thus, the more the coupling - methods, props. - the harder it is to change callee code without breaking all the code that uses it.
contemplating coupling
- Referencing even a single prop., method couples two objects.
- Obviously coupling is necessary for creating software.
- Given the 'lock step' nature of coupling we want to both limit and isolate it. This goal simply goes along with general software dev. principles.
- The fewer objects we have to talk to, the lower the coupling.
- If I need to make, say, 20 different method calls the coupling is lower if all 20 calls are to one class/object, vice those same methods spread over several classes/objects.
Most Knowledge causes crazy coupling
Here we have an Employee
that has a Person
that has a 'Address'
public class Employee {
public Person me = new Person();
}
public class Person {
public Address home = new Address();
}
public class Address {
public string street;
}
To get the street I must call: myEmployee.me.home.street
. This is 180 degree opposite of the principle of least knowledge. I have to know about the internals, the composite structure, of the Employee
, Person
, and Address
classes.
This defective class design forces me to know about all those classes and thus myEmployee.me.home.street
couples me (the caller object) to no less than 3 classes - to get only a single property!
Least Knowledge Saves the Day
If I talk to only the Employee
class I am applying the least knowledge principle per se, and by doing so we automatically limit coupling to only that class, and at the same time isolate coupling to that one class.
By adding all the needed properties in the Employee
class we fix the coupling.
thus
public class Employee {
public Person me = new Person();
public string street { return me.home.street; }
}
Allows me to call: myEmployee.street
-
- I "know" only
Employee
- I am coupled to only
Employee
- no matter how complex its structure.
Least Knowledge all the way down
We decoupled myEmployee from Person
and Address
, and ideally we should continue applying least knowledge by adding pass through properties such that Employee
only talks to Person
and Person
only talks to Address