Our latest code-quality theme was the Law of Demeter, more descriptively known as The Principle of Least Knowledge or Stay Out of My Guts. Applying this rule helps you reduce dependencies in your code and avoid painful coupling (where to change A, you have to change B, which means you have to change C – a familiar litany in lots of our code).
We found several examples relevant to the Law of Demeter in our code, including
- a data-holder class whose only methods manipulate its private members (sort of like a high-maintenance struct) – we converted this from a Shame item to a Fame item by replacing the data-holder with a simple primitive object
- a couple of train wrecks with four successive method calls
You may enjoy the demotivational posters we came up with to illustrate the Law of Demeter: