Clean Code with Multiple Classes in C++

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: Refer 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. This results in a dependency that's best avoided for clearer separation of concerns.

#include <vector>

class Item {
public:
    Item(double p, int q) : price(p), quantity(q) {}

    double getPrice() const {
        return price;
    }

    int getQuantity() const {
        return quantity;
    }

private:
    double price;
    int quantity;
};

class ShoppingCart {
public:
    // Calculate total price by directly accessing price and quantity of each Item
    double calculateTotalPrice() const {
        double total = 0;
        for (const auto& item : items) {
            total += item.getPrice() * item.getQuantity();  // Feature Envy: ShoppingCart is overly interested in Item
        }
        return total;
    }

    void addItem(const Item& item) {
        items.push_back(item);
    }

private:
    std::vector<Item> items;
};

To refactor, move the logic to the Item class, allowing each Item to calculate its own total, thus reducing dependency and distributing responsibility:

class Item {
public:
    Item(double p, int q) : price(p), quantity(q) {}

    // Each Item is responsible for calculating its own total
    double calculateTotal() const {
        return price * quantity;
    }

private:
    double price;
    int quantity;
};

class ShoppingCart {
public:
    // ShoppingCart now uses Item's method to calculate the total price
    double calculateTotalPrice() const {
        double total = 0;
        for (const auto& item : items) {
            total += item.calculateTotal();
        }
        return total;
    }

    void addItem(const Item& item) {
        items.push_back(item);
    }

private:
    std::vector<Item> items;
};

Inappropriate Intimacy

Inappropriate Intimacy occurs when a class is overly dependent on the internal details of another class. This can lead to tight coupling and a lack of encapsulation.

#include <iostream>
#include <string>

class Book {
public:
    Book(const std::string& t, const std::string& a) : title(t), author(a) {}

    std::string getTitle() const {
        return title;
    }

    std::string getAuthor() const {
        return author;
    }

private:
    std::string title;
    std::string author;
};

class Library {
public:
    // Directly accessing Book's details can lead to inappropriate intimacy
    void printBookDetails(const Book& book) const {
        std::cout << "Title: " << book.getTitle() << "\n";  // Accessing Book's internal data
        std::cout << "Author: " << book.getAuthor() << "\n";  // Accessing Book's internal data
    }
};

To refactor, allow the Book class to handle its own representation, enabling it to encapsulate its details and encouraging separation of concerns:

class Book {
public:
    Book(const std::string& t, const std::string& a) : title(t), author(a) {}

    // Book is now responsible for its own details representation
    std::string getDetails() const {
        return "Title: " + title + "\nAuthor: " + author;
    }

private:
    std::string title;
    std::string author;
};

class Library {
public:
    // Library now relies on Book to provide its details, reducing inappropriate intimacy
    void printBookDetails(const Book& book) const {
        std::cout << book.getDetails() << "\n";
    }
};

Message Chains

Message Chains occur when classes need to traverse multiple objects to access the methods they require. This indicates a lack of clear abstraction and can make code difficult to read and maintain.

#include <string>

class ZipCode {
public:
    std::string getPostalCode() const {
        return "90210";
    }
};

class Address {
public:
    Address(ZipCode z) : zipCode(z) {}

    ZipCode getZipCode() const {
        return zipCode;
    }

private:
    ZipCode zipCode;
};

class User {
public:
    User(Address a) : address(a) {}

    Address getAddress() const {
        return address;
    }

private:
    Address address;
};

// Usage
User user(Address(ZipCode()));
std::string postalCode = user.getAddress().getZipCode().getPostalCode();  // Message chains, accessing through multiple objects

To simplify, encapsulate the access within methods, providing a clearer and more direct interface:

class Address {
public:
    Address(ZipCode z) : zipCode(z) {}

    // Delegate access to the postal code to the Address class
    std::string getPostalCode() const {
        return zipCode.getPostalCode();
    }

private:
    ZipCode zipCode;
};

class User {
public:
    User(Address a) : address(a) {}

    // User now provides direct access to its postal code
    std::string getUserPostalCode() const {
        return address.getPostalCode();
    }

private:
    Address address;
};

// Usage
User user(Address(ZipCode()));
std::string postalCode = user.getUserPostalCode();  // Simplified access

Middle Man

A Middle Man problem occurs when a class primarily exists to delegate its functionalities to another class without adding any functionality of its own. This can create unnecessary complexity in your class design.

class Service {
public:
    void performAction() {
        // Action performed
    }
};

class Controller {
private:
    Service service;

public:
    // Controller is just passing the call to Service
    void execute() {
        service.performAction();
    }
};

To refactor, remove the unnecessary middle man or reassign responsibility, resulting in a more streamlined and efficient design:

class Service {
public:
    void performAction() {
        // Action performed
    }
};

// Usage
Service service;
service.performAction();  // Direct call, removing the unnecessary middle man

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

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal