Lesson 3
Law of Demeter: Limiting Object Interactions for Cleaner Code
Introduction

Welcome to the third lesson of the Applying Clean Code Principles in Scala course. In our journey so far, we've discussed the importance of the DRY (Don't Repeat Yourself) principle for eliminating 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 was introduced by Karl J. Lieberherr and 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 X of the class C should only call methods of:

  • Class C itself
  • An object created by X
  • An object passed as an argument to X
  • An object held in an instance variable of C
  • A constant defined in the class

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:

Scala
1class Car: 2 def start(): Unit = 3 checkFuel() 4 ignite() 5 6 private def checkFuel(): Unit = 7 println("Checking fuel level...") 8 9 private def ignite(): Unit = 10 println("Igniting the engine...")

In this example, the start method interacts solely with methods within the Car class itself. This shows how you maintain clear boundaries by adhering to the Law of Demeter.

Second Rule Example

Next, a method can interact with the objects it creates:

Scala
1class Library: 2 def borrowBook(title: String): Book = 3 val book = Book(title) 4 book.issue() 5 book 6 7class Book(val title: String): 8 def issue(): Unit = 9 println(s"Book issued: $title")

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

Third Rule Example

Continuing, let's look at interacting with objects passed as arguments:

Scala
1class Printer: 2 def print(document: Document): Unit = 3 document.sendToPrinter() 4 5class Document: 6 def sendToPrinter(): Unit = 7 println("Document is being printed...")

The Printer class method print communicates with the Document object passed as an argument, aligning with the Law of Demeter by limiting communication to direct method parameters. 📄

Fourth Rule Example

Objects held in instance variables of a class can also be accessed:

Scala
1class House: 2 private val door = Door() 3 4 def lockHouse(): Unit = 5 door.close() 6 7class Door: 8 def close(): Unit = 9 println("Door is closed.")

In this example, the House class interacts with its door through the lockHouse method, showcasing compliance by interacting with an object it holds in an instance variable. 🏠

Fifth Rule Example

Finally, let's see a method interacting with class-level constants. While such constants are convenient, they should be used with understanding, as they can lead to shared state issues in larger applications:

Scala
1object TemperatureConverter: 2 private val ConversionFactor = 9.0 / 5.0 3 4 def celsiusToFahrenheit(celsius: Int): Int = 5 (celsius * ConversionFactor + 32).toInt

Here, ConversionFactor is defined with val to indicate that it's a constant. This is compliant with the Law of Demeter when accessed within its domain. 🌡️

Violation Example

Here's an example that violates the Law of Demeter:

Scala
1class Person(address: Address): 2 def getAddressDetails(): String = 3 s"Address: ${address.firstName} ${address.lastName}, ${address.street}, " + 4 s"${address.city}, ${address.country}, ZipCode: ${address.zipCode}" 5 6class Address( 7 val firstName: String, 8 val lastName: String, 9 val street: String, 10 val city: String, 11 val country: String, 12 val zipCode: String 13)

In this case, Person is directly accessing multiple fields through Address, leading to tight coupling. Person relies on the internal structure of Address, which might result in fragile code.

Refactored Example

Let's refactor the previous code to adhere to the Law of Demeter:

Scala
1class Person(address: Address): 2 def getAddressDetails(): String = 3 address.fullAddress 4 5class Address( 6 val firstName: String, 7 val lastName: String, 8 val street: String, 9 val city: String, 10 val country: String, 11 val zipCode: String 12): 13 def fullAddress: String = 14 s"$firstName $lastName, $street, $city, $country, ZipCode: $zipCode"

By encapsulating all the address details within the fullAddress method in the Address class, the dependency is minimized, and Person no longer accesses the internals of Address directly.

Summary and Next Steps

The Law of Demeter plays a vital role in writing clean, modular code by ensuring objects only interact with their closest dependencies. By understanding and implementing these guidelines, you enhance the modularity and maintainability of your code. As you move on to the practice exercises, challenge yourself to apply these principles and evaluate your code's interactions. Keep these lessons in mind as essential steps toward mastering clean code! 🌟

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.