An antique toy train with two carriages, that almost stays on the track.

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).

Related texts

A single frosted leaf with clear contours and veins.

TDD in the context of writing code to be read

Wunder Baum hanging from a car window (Known as Little Trees in most English-speaking countries)

Wunderbaum testing