Lesson 1
Class Collaboration and Coupling
Introduction

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.

Overview of Class Collaboration Challenges

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.

Problems Arising During Class Collaboration

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

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 in TypeScript:

TypeScript
1class ShoppingCart { 2 private items: Item[] = []; 3 4 public calculateTotalPrice(): number { 5 return this.items.reduce((total, item) => total + item.getPrice() * item.getQuantity(), 0); 6 } 7} 8 9class Item { 10 private price: number; 11 private quantity: number; 12 13 constructor(price: number, quantity: number) { 14 this.price = price; 15 this.quantity = quantity; 16 } 17 18 public getPrice(): number { 19 return this.price; 20 } 21 22 public getQuantity(): number { 23 return this.quantity; 24 } 25}

In this scenario, calculateTotalPrice() in ShoppingCart overly accesses data from Item, indicating feature envy.

To refactor, consider moving the logic to the Item class:

TypeScript
1class ShoppingCart { 2 private items: Item[] = []; 3 4 public calculateTotalPrice(): number { 5 return this.items.reduce((total, item) => total + item.calculateTotal(), 0); 6 } 7} 8 9class Item { 10 private price: number; 11 private quantity: number; 12 13 constructor(price: number, quantity: number) { 14 this.price = price; 15 this.quantity = quantity; 16 } 17 18 public calculateTotal(): number { 19 return this.price * this.quantity; 20 } 21}

Now, each Item calculates its own total, reducing dependency and distributing responsibility appropriately. ✔️

Inappropriate Intimacy

Inappropriate Intimacy occurs when a class is overly dependent on the internal details of another class. Here's an example in TypeScript:

TypeScript
1class Library { 2 private book: Book; 3 4 constructor(book: Book) { 5 this.book = book; 6 } 7 8 public printBookDetails(): void { 9 console.log(`Title: ${this.book.getTitle()}`); 10 console.log(`Author: ${this.book.getAuthor()}`); 11 } 12} 13 14class Book { 15 private title: string; 16 private author: string; 17 18 constructor(title: string, author: string) { 19 this.title = title; 20 this.author = author; 21 } 22 23 public getTitle(): string { 24 return this.title; 25 } 26 27 public getAuthor(): string { 28 return this.author; 29 } 30}

In this scenario, the Library class relies too heavily on the details of the Book class, demonstrating inappropriate intimacy.

To refactor, allow the Book class to handle its own representation:

TypeScript
1class Library { 2 private book: Book; 3 4 constructor(book: Book) { 5 this.book = book; 6 } 7 8 public printBookDetails(): void { 9 console.log(this.book.getDetails()); 10 } 11} 12 13class Book { 14 private title: string; 15 private author: string; 16 17 constructor(title: string, author: string) { 18 this.title = title; 19 this.author = author; 20 } 21 22 public getDetails(): string { 23 return `Title: ${this.title}\nAuthor: ${this.author}`; 24 } 25}

This adjustment enables Book to encapsulate its own details, encouraging better encapsulation and separation of concerns. 🛡️

Message Chains

Message Chains occur when classes need to traverse multiple objects to access the methods they require. Here's a demonstration in TypeScript:

TypeScript
1class User { 2 private address: Address; 3 4 constructor(address: Address) { 5 this.address = address; 6 } 7 8 public getAddress(): Address { 9 return this.address; 10 } 11} 12 13class Address { 14 private zipCode: ZipCode; 15 16 constructor(zipCode: ZipCode) { 17 this.zipCode = zipCode; 18 } 19 20 public getZipCode(): ZipCode { 21 return this.zipCode; 22 } 23} 24 25class ZipCode { 26 public getPostalCode(): string { 27 return "90210"; 28 } 29} 30 31// Usage 32const user = new User(new Address(new ZipCode())); 33console.log(user.getAddress().getZipCode().getPostalCode());

The chain user.getAddress().getZipCode().getPostalCode() illustrates this problem.

To simplify, encapsulate the access within methods:

TypeScript
1class User { 2 private address: Address; 3 4 constructor(address: Address) { 5 this.address = address; 6 } 7 8 public getUserPostalCode(): string { 9 return this.address.getPostalCode(); 10 } 11} 12 13class Address { 14 private zipCode: ZipCode; 15 16 constructor(zipCode: ZipCode) { 17 this.zipCode = zipCode; 18 } 19 20 public getPostalCode(): string { 21 return this.zipCode.getPostalCode(); 22 } 23} 24 25// Usage 26const user = new User(new Address(new ZipCode())); 27console.log(user.getUserPostalCode());

This adjustment makes the User class responsible for retrieving its postal code, creating a clearer and more direct interface. 📬

Middle Man

A Middle Man problem occurs when a class primarily exists to delegate its functionalities. Here's an example in TypeScript:

TypeScript
1class Controller { 2 private service: Service; 3 4 constructor(service: Service) { 5 this.service = service; 6 } 7 8 public execute(): void { 9 this.service.performAction(); 10 } 11} 12 13class Service { 14 public performAction(): void { 15 // Action performed 16 } 17}

The Controller doesn't do much beyond delegating to Service.

To refactor, simplify delegation or reassign responsibilities:

TypeScript
1class Service { 2 public performAction(): void { 3 // Action performed 4 } 5} 6 7// Usage 8const service = new Service(); 9service.performAction();

By removing the unnecessary middle man, the design becomes more streamlined and efficient. 🔥

Summary and Practice Heads-Up

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! 🌟

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