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. 🤓
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 static field
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. 🚀
For the first point, a method should only access its class's methods:
TypeScript1class Car { 2 public start() { 3 this.checkFuel(); 4 this.ignite(); 5 } 6 7 private checkFuel() { 8 console.log("Checking fuel level..."); 9 } 10 11 private ignite() { 12 console.log("Igniting the engine..."); 13 } 14}
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.
Next, a method can interact with the objects it creates:
TypeScript1class Library { 2 public borrowBook(title: string): Book { 3 const book = new Book(title); 4 book.issue(); 5 return book; 6 } 7} 8 9class Book { 10 private title: string; 11 12 constructor(title: string) { 13 this.title = title; 14 } 15 16 public issue() { 17 console.log("Book issued: " + this.title); 18 } 19}
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
. 📚
Continuing, let's look at interacting with objects passed as arguments:
TypeScript1class Printer { 2 public print(document: Document) { 3 document.sendToPrinter(); 4 } 5} 6 7class Document { 8 public sendToPrinter() { 9 console.log("Document is being printed..."); 10 } 11}
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. 🖨️
Objects held in instance variables of a class can also be accessed:
TypeScript1class House { 2 private door = new Door(); 3 4 public lockHouse() { 5 this.door.close(); 6 } 7} 8 9class Door { 10 public close() { 11 console.log("Door is closed."); 12 } 13}
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. 🏠
Finally, let's see a method interacting with static fields. While static fields are convenient, they should generally be used cautiously since they can lead to shared state issues in larger applications:
TypeScript1class TemperatureConverter { 2 private static readonly conversionFactor = 9.0 / 5.0; 3 4 public celsiusToFahrenheit(celsius: number): number { 5 return Math.round(celsius * TemperatureConverter.conversionFactor + 32); 6 } 7}
Here, conversionFactor
is defined as a readonly
variable to indicate that it's a constant, and to ensure correct calculations, the division is a double. Accessing static fields like this complies with the Law of Demeter. 🌡️
Here's an example that violates the Law of Demeter:
TypeScript1class Person { 2 private address: Address; 3 4 constructor(address: Address) { 5 this.address = address; 6 } 7 8 public getAddressDetails(): string { 9 return "Address: " + this.address.getFirstName() + " " + this.address.getLastName() + 10 ", " + this.address.getStreet() + 11 ", " + this.address.getCity() + 12 ", " + this.address.getCountry() + 13 ", ZipCode: " + this.address.getZipCode(); 14 } 15} 16 17class Address { 18 private firstName: string; 19 private lastName: string; 20 private street: string; 21 private city: string; 22 private country: string; 23 private zipCode: string; 24 25 constructor(firstName: string, lastName: string, street: string, city: string, country: string, zipCode: string) { 26 this.firstName = firstName; 27 this.lastName = lastName; 28 this.street = street; 29 this.city = city; 30 this.country = country; 31 this.zipCode = zipCode; 32 } 33 34 public getFirstName(): string { 35 return this.firstName; 36 } 37 38 public getLastName(): string { 39 return this.lastName; 40 } 41 42 public getStreet(): string { 43 return this.street; 44 } 45 46 public getCity(): string { 47 return this.city; 48 } 49 50 public getCountry(): string { 51 return this.country; 52 } 53 54 public getZipCode(): string { 55 return this.zipCode; 56 } 57}
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.
Let's refactor the previous code to adhere to the Law of Demeter:
TypeScript1class Person { 2 private address: Address; 3 4 constructor(address: Address) { 5 this.address = address; 6 } 7 8 public getAddressDetails(): string { 9 return this.address.getAddressLine(); 10 } 11} 12 13class Address { 14 private firstName: string; 15 private lastName: string; 16 private street: string; 17 private city: string; 18 private country: string; 19 private zipCode: string; 20 21 constructor(firstName: string, lastName: string, street: string, city: string, country: string, zipCode: string) { 22 this.firstName = firstName; 23 this.lastName = lastName; 24 this.street = street; 25 this.city = city; 26 this.country = country; 27 this.zipCode = zipCode; 28 } 29 30 public getAddressLine(): string { 31 return this.firstName + " " + this.lastName + 32 ", " + this.street + 33 ", " + this.city + 34 ", " + this.country + 35 ", ZipCode: " + this.zipCode; 36 } 37}
By encapsulating all the address details within the getAddressLine
method in the Address
class, the dependency is minimized, and Person
no longer accesses Address
's internals directly.
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! 🌟