Welcome to the very first lesson of the "Clean Code with Multiple Classes" course! 🎉 This course aims to guide you in writing code that's easy to understand, maintain, and enhance. Within the broader scope of clean coding, effective class collaboration is crucial for building well-structured applications. In this lesson, we will delve into the intricacies of class collaboration and coupling—key factors that can make or break the maintainability of your software. Specifically, we'll address some common "code smells" that indicate problems in class interactions and explore ways to resolve them.
Let's dive into the challenges of class collaboration by focusing on four common code smells:
- Feature Envy: Occurs when a method in one class is overly interested in methods or data in another class.
- Inappropriate Intimacy: Describes a situation where two classes are too closely interconnected, sharing private details.
- Message Chains: Refers to sequences of method calls across several objects, indicating a lack of clear abstraction.
- Middle Man: Exists when a class mainly delegates its behavior to another class without adding functionality.
Understanding these code smells will enable you to improve your class designs, resulting in cleaner and more maintainable code.
These code smells can significantly impact system design and maintainability. Let's consider their implications:
- They can lead to tightly coupled classes, making them difficult to modify or extend. 🔧
- Code readability decreases, as it becomes unclear which class is responsible for which functionality.
Addressing these issues often results in code that's not only easier to read but also more flexible and scalable. Tackling these problems can markedly enhance software architecture, making it more robust and adaptable.
Feature Envy occurs when a method in one class is more interested in the fields or methods of another class than its own. Here's an example:
Java1class ShoppingCart { 2 private List<Item> items = new ArrayList<>(); 3 4 public double calculateTotalPrice() { 5 double total = 0; 6 for (Item item : items) { 7 total += item.getPrice() * item.getQuantity(); 8 } 9 return total; 10 } 11} 12 13class Item { 14 private double price; 15 private int quantity; 16 17 public double getPrice() { 18 return price; 19 } 20 21 public int getQuantity() { 22 return quantity; 23 } 24}
In this scenario, calculateTotalPrice()
in ShoppingCart
overly accesses data from Item
, indicating feature envy.
To refactor, consider moving the logic to the Item
class:
Java1class ShoppingCart { 2 private List<Item> items = new ArrayList<>(); 3 4 public double calculateTotalPrice() { 5 double total = 0; 6 for (Item item : items) { 7 total += item.calculateTotal(); 8 } 9 return total; 10 } 11} 12 13class Item { 14 private double price; 15 private int quantity; 16 17 public double getPrice() { 18 return price; 19 } 20 21 public int getQuantity() { 22 return quantity; 23 } 24 25 public double calculateTotal() { 26 return price * quantity; 27 } 28}
Now, each Item
calculates its own total, reducing dependency and distributing responsibility appropriately. ✔️
Inappropriate Intimacy occurs when a class is overly dependent on the internal details of another class. Here's an example:
Java1class Library { 2 private Book book; 3 4 public void printBookDetails() { 5 System.out.println("Title: " + book.getTitle()); 6 System.out.println("Author: " + book.getAuthor()); 7 } 8} 9 10class Book { 11 private String title; 12 private String author; 13 14 public String getTitle() { 15 return title; 16 } 17 18 public String getAuthor() { 19 return author; 20 } 21}
In this scenario, the Library
class relies too heavily on the details of the Book
class, demonstrating inappropriate intimacy. The key distinction between Inappropriate Intimacy and Feature Envy is that inappropriate intimacy involves a significant intertwining between two classes, while feature envy is about a method's excessive interest in another class's data or behavior instead of its own.
To refactor, allow the Book
class to handle its own representation:
Java1class Library { 2 private Book book; 3 4 public void printBookDetails() { 5 System.out.print(book.getDetails()); 6 } 7} 8 9class Book { 10 private String title; 11 private String author; 12 13 public String getDetails() { 14 return "Title: " + title + "\nAuthor: " + author; 15 } 16}
This adjustment enables Book
to encapsulate its own details, encouraging better encapsulation and separation of concerns. 🛡️
Message Chains occur when classes need to traverse multiple objects to access the methods they require. Here's a demonstration:
Java1class User { 2 private Address address; 3 4 public Address getAddress() { 5 return address; 6 } 7} 8 9class Address { 10 private ZipCode zipCode; 11 12 public ZipCode getZipCode() { 13 return zipCode; 14 } 15} 16 17class ZipCode { 18 public String getPostalCode() { 19 return "90210"; 20 } 21} 22 23// Usage 24User user = new User(); 25user.getAddress().getZipCode().getPostalCode();
The chain user.getAddress().getZipCode().getPostalCode()
illustrates this problem.
To simplify, encapsulate the access within methods:
Java1class User { 2 private Address address; 3 4 public String getUserPostalCode() { 5 return address.getPostalCode(); 6 } 7} 8 9class Address { 10 private ZipCode zipCode; 11 12 public String getPostalCode() { 13 return zipCode.getPostalCode(); 14 } 15} 16 17// Usage 18User user = new User(); 19user.getUserPostalCode();
This adjustment makes the User
class responsible for retrieving its postal code, creating a clearer and more direct interface. 📬
A Middle Man problem occurs when a class primarily exists to delegate its functionalities. Here's an example:
Java1class Controller { 2 private Service service; 3 4 public void execute() { 5 service.performAction(); 6 } 7} 8 9class Service { 10 public void performAction() { 11 // Action performed 12 } 13}
The Controller
doesn't do much beyond delegating to Service
.
To refactor, simplify delegation or reassign responsibilities:
Java1class Service { 2 public void performAction() { 3 // Action performed 4 } 5} 6 7// Usage 8Service service = new Service(); 9service.performAction();
By removing the unnecessary middle man, the design becomes more streamlined and efficient. 🔥
In this lesson, you've explored several code smells associated with suboptimal class collaboration and coupling, including Feature Envy, Inappropriate Intimacy, Message Chains, and Middle Man. By identifying and refactoring these smells, you can elevate your code's clarity and maintainability.
Get ready to put these concepts into practice with upcoming exercises, where you'll identify and refactor code smells, strengthening your skills. Keep striving for cleaner, more effective code! 🌟