Applying Clean Code Principles with Ruby: Understanding the Law of Demeter
Introduction
Welcome to the third lesson of the "Applying Clean Code Principles" course. In our journey so far, we've discussed the importance of the DRY (Don't Repeat Yourself) principle to eliminate redundancy in code. We followed that with the KISS (Keep It Simple, Stupid) principle, which highlights the value of simplicity in software development. Today, our spotlight is on the Law of Demeter — a key guideline in object-oriented programming. By limiting the knowledge that an object has about other objects, this lesson will guide you in crafting more maintainable and modular code. 🤓
Understanding the Law of Demeter
The Law of Demeter suggests that an object should only communicate with its immediate collaborators, avoiding the entire system. By reducing dependency between parts, you'll find your code easier to maintain and scale. In simple terms, a method in a class should only call methods of:
- The class itself
- An object created within the method
- An object passed as an argument to the method
- An object held in an instance variable of the class
- A class constant
With these principles, you control how parts of your application interact, leading to a more organized structure. Let's explore how this works with examples. 🚀
First Rule Example
For the first point, a method should only access its own class's methods:
In this example, the start method interacts solely with methods within the Car class itself. This shows how you maintain clear boundaries adhering to the Law of Demeter.
Second Rule Example
Next, a method can interact with the objects it creates:
Here, the Library class creates a Book and calls the issue method on it. This usage pattern complies with the Law of Demeter, where Library interacts with the newly created Book. 📚
