Dependency graphs as a design tool
In languages without automatic memory management, you need to keep track of the references to memory you allocate. One way to model that is a graph with no circular paths. It becomes a kind of ownership system for the code structures. That will also show in what files you need to import for your code. (You should be able to (manually) sort your files, so that the imports in each file are only of files that come before it.) That will then also be a guide of who gets to talk to whom.
Law of Demeter, “don’t talk to strangers”, is also easier to remember, in a language that forces you to null-check a lot. It is riskier to talk to your neighbours neighbours if they might have been deallocated. Following the Law of Demeter aims at loosely coupled architecture, and code that is easier to change. Loosely coupled architecture can also be viewed as deliberately coupled architecture. To craft those relationship graphs we can reuse the methods for managing memory.
It is good that not all languages require you to allocate memory by hand. The skills required to design a system that does not leak memory, might have other usages though. Try that the next time you find yourself in a codebase where access to objects are expected to work from all over the place. Code where changing one signature ripples through the entire system.
Questions to ask:
- If one object had to both create and destroy this object, who would do that?
- What objects depend on this object existing?
- What objects does this object depend on, that others also need?
Keeping a tidy object graph helps with memory management, but also with separating concerns and easy to change code.
BONUS:
Interfaces can be used to avoid import loops in patterns like observer-observable. And it also creates an abstraction layer for the design (if done properly).
Comment on the blog!
Create a comment by emailing me.
Open an email to start writing.I will then add the comment to the post.