Vlad's Roam Garden

Powered by 🌱Roam Garden

Write shy code

Your code should only talk to it's immediate collaborators

This minimizes coupling, leading to the more resilient code.

If you have to reach deep into some object that may serve as indication that there is something wrong with the level of abstraction of your code - two levels that try to interact are too far removed.

The long set of chained calls like page.blocks[0].header.font can serve as an indicator that you may be reaching out too deep into the object.

At the same time there are styles of code that employ a long chain of code that are totally fine. The examples include

I was actually somewhat weary of these initially because of usage of long chain of calls.

But the important difference here is that we don't violate the object encapsulation when we use transformation pipelines - we just apply set of modification to some data.

This is sometimes called the Law of Demeter. The Pragmatic Programmers call it “Writing Shy Code.” In either case it comes down to making sure that modules know only about their immediate collaborators and do not know the navigation map of the whole system.
If many modules used some form of the statement a.getB().getC(), then it would be difficult to change the design and architecture to interpose a Q between B and C. You’d have to find every instance of a.getB().getC() and convert it to a.getB().getQ().getC(). This is how architectures become rigid. Too many modules know too much about the architecture.
Rather we want our immediate collaborators to offer all the services we need. We should not have to roam through the object graph of the system, hunting for the method we want to call. Rather we should simply be able to say:

somehow when you follow other principles, it's relatively easy to comply with this, but I've thought of this as a challenge before