Welcome to the third lesson of the "Applying Clean Code Principles" course. In our journey so far, we've talked about 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 own class's methods:
Java1class Car { 2 public void start() { 3 this.checkFuel(); 4 this.ignite(); 5 } 6 7 private void checkFuel() { 8 System.out.println("Checking fuel level..."); 9 } 10 11 private void ignite() { 12 System.out.println("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:
Java1class Library { 2 public Book borrowBook(String title) { 3 Book book = new Book(title); 4 book.issue(); 5 return book; 6 } 7} 8 9class Book { 10 private String title; 11 12 public Book(String title) { 13 this.title = title; 14 } 15 16 public void issue() { 17 System.out.println("Book issued: " + 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:
Java1class Printer { 2 public void print(Document document) { 3 document.sendToPrinter(); 4 } 5} 6 7class Document { 8 public void sendToPrinter() { 9 System.out.println("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:
Java1class House { 2 private Door door = new Door(); 3 4 public void lockHouse() { 5 door.close(); 6 } 7} 8 9class Door { 10 public void close() { 11 System.out.println("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:
Java1class TemperatureConverter { 2 private static final double conversionFactor = 9.0 / 5.0; 3 4 public int celsiusToFahrenheit(int celsius) { 5 return (int)((celsius * conversionFactor) + 32); 6 } 7}
Here, conversionFactor
is defined as a final
variable to indicate that it's a constant and to ensure correct calculations, the division is a double. Accessing static fields like this is compliant with the Law of Demeter. 🌡️
Here's an example that violates the Law of Demeter:
Java1class Person { 2 private Address address; 3 4 public String getAddressDetails() { 5 return "Address: " + address.getFirstName() + " " + address.getLastName() + 6 ", " + address.getStreet() + 7 ", " + address.getCity() + 8 ", " + address.getCountry() + 9 ", ZipCode: " + address.getZipCode(); 10 } 11} 12 13class Address { 14 private String firstName; 15 private String lastName; 16 private String street; 17 private String city; 18 private String country; 19 private String zipCode; 20 21 public String getFirstName() { 22 return firstName; 23 } 24 25 public String getLastName() { 26 return lastName; 27 } 28 29 public String getStreet() { 30 return street; 31 } 32 33 public String getCity() { 34 return city; 35 } 36 37 public String getCountry() { 38 return country; 39 } 40 41 public String getZipCode() { 42 return zipCode; 43 } 44}
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:
Java1class Person { 2 private Address address; 3 4 public String getAddressDetails() { 5 return address.getAddressLine(); 6 } 7} 8 9class Address { 10 private String firstName; 11 private String lastName; 12 private String street; 13 private String city; 14 private String country; 15 private String zipCode; 16 17 public String getAddressLine() { 18 return firstName + " " + lastName + 19 ", " + street + 20 ", " + city + 21 ", " + country + 22 ", ZipCode: " + zipCode; 23 } 24}
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! 🌟