Scooping with the Law of Demeter in Python: An analogy of creating readable and maintainable code 🍨

Benjamin Lo
2 min readJan 12, 2023
The Law Of Demeter (LoD) explained using ice cream

Just like how a scoop of ice cream should only reach into the container it has immediate access to, the Law of Demeter (LoD, also known as the Principle of Least Knowledge) states that an object in your code should only interact with its immediate neighbours. In this article, we will explore how following this principle can make your code more readable and maintainable, using the metaphor of organised ice cream scoops for a better understanding.

In Python, following LoD means avoiding “train-wrecks” of method calls, just like how a train-wreck of ice cream scoops would be difficult to manage and understand. By this we mean that when an object makes several method calls on other objects each call returns a new object and then finally calling a method on the final object. This makes the code hard to understand and reason about, just like a train-wreck of ice cream scoops would be hard to eat and enjoy (haha).

A simple example of violating LoD is shown below when trying to access a certain flavour of ice cream deep inside a nested container structure.

A common way of accessing the many ice cream flavours in our data

The problem

The above doesn’t obey LoD because our code is trying to reach into a nested container to access an ice cream flavour, making it difficult to understand what data is being accessed and why.

To put it another way — It’s problematic in that it is tightly coupled to different parts of the code together. This in turn creates a dependency on the specific structure of the container and the actual location of an ice cream flavour. What we are left then, is something that is hard to modify without causing unintended consequences. You can see now that this poses a higher risk of errors so it’s no longer open to extension.

The solution

A better way to follow LoD is to:

  1. Create a class that represents the container structure. And,
  2. Provide methods to access our inner data.

Summary

By following LoD, the code is more readable and maintainable, making it easier to understand what ice cream flavour is being accessed and how it is being used.

It’s a simple, yet, powerful principle that can help to create more robust and maintainable code, just like how an organised container of ice cream scoops can help your enjoy the ice cream better.

--

--

Benjamin Lo

A Senior Software Engineer with an unquenchable thirst for learning