Introduction

Welcome to the very first lesson of the "Clean Code with Multiple Structs in Go" 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 struct collaboration is crucial for building well-structured applications. In this lesson, we will delve into the intricacies of struct 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 struct interactions and explore ways to resolve them.

Overview of Struct Collaboration Challenges

Let's dive into the challenges of struct collaboration by focusing on four common code smells:

  • Feature Envy: Occurs when a method in one struct is overly interested in methods or data in another struct.
  • Inappropriate Intimacy: Describes a situation where two structs are too closely interconnected, sharing private details.
  • Message Chains: Refer to sequences of method calls across several structs, indicating a lack of clear abstraction.
  • Middle Man: Exists when a struct mainly delegates its behavior to another struct without adding functionality.

Understanding these code smells will enable you to improve your struct designs, resulting in cleaner and more maintainable code.

Problems Arising During Struct Collaboration

These code smells can significantly impact system design and maintainability. Let's consider their implications:

  • They can lead to tightly coupled structs, making them difficult to modify or extend. 🔧
  • Code readability decreases, as it becomes unclear which struct 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 struct is more interested in the fields or methods of another struct than its own. Here's an example in Go:

package main

import "fmt"

type Item struct {
    Price    float64
    Quantity int
}

type ShoppingCart struct {
    Items []Item
}

func (sc ShoppingCart) CalculateTotalPrice() float64 {
    total := 0.0
    for _, item := range sc.Items {
        // Feature Envy: The ShoppingCart method is overly interested in the internal fields of Item
        total += item.Price * float64(item.Quantity)
    }
    return total
}

func main() {
    cart := ShoppingCart{
        Items: []Item{
            {Price: 5.0, Quantity: 2},
            {Price: 10.0, Quantity: 1},
        },
    }
    fmt.Printf("Total Price: %.2f\n", cart.CalculateTotalPrice())
}

In this scenario, CalculateTotalPrice in ShoppingCart overly accesses data from Item, indicating feature envy.

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

package main

import "fmt"

type Item struct {
    Price    float64
    Quantity int
}

func (item Item) CalculateTotal() float64 {
    return item.Price * float64(item.Quantity)
}

type ShoppingCart struct {
    Items []Item
}

func (sc ShoppingCart) CalculateTotalPrice() float64 {
    total := 0.0
    for _, item := range sc.Items {
        total += item.CalculateTotal()
    }
    return total
}

func main() {
    cart := ShoppingCart{
        Items: []Item{
            {Price: 5.0, Quantity: 2},
            {Price: 10.0, Quantity: 1},
        },
    }
    fmt.Printf("Total Price: %.2f\n", cart.CalculateTotalPrice())
}

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

Inappropriate Intimacy

Inappropriate Intimacy occurs when a struct is overly dependent on the internal details of another struct. In Go, package-level access is used to control visibility. Here's an example:

package main

import "fmt"

type Book struct {
    Title  string
    Author string
}

type Library struct {
    Book Book
}

func (l Library) PrintBookDetails() {
    // Inappropriate Intimacy: The Library struct relies too heavily on directly accessing
    // the internal details of the Book struct, leading to a high degree of coupling.
    fmt.Printf("Title: %s\nAuthor: %s\n", l.Book.Title, l.Book.Author)
}

func main() {
    lib := Library{
        Book: Book{Title: "Go Programming", Author: "John Doe"},
    }
    lib.PrintBookDetails()
}

The Library struct relies too heavily on the details of the Book struct, demonstrating inappropriate intimacy.

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

package main

import "fmt"

type Book struct {
    Title  string
    Author string
}

func (b Book) GetDetails() string {
    return fmt.Sprintf("Title: %s\nAuthor: %s\n", b.Title, b.Author)
}

type Library struct {
    Book Book
}

func (l Library) PrintBookDetails() {
    fmt.Print(l.Book.GetDetails())
}

func main() {
    lib := Library{
        Book: Book{Title: "Go Programming", Author: "John Doe"},
    }
    lib.PrintBookDetails()
}

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

Message Chains

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

package main

import "fmt"

type Address struct {
    ZipCode ZipCode
}

type ZipCode struct {
    Code string
}

type User struct {
    Address Address
}

func main() {
    user := User{
        Address: Address{
            ZipCode: ZipCode{Code: "90210"},
        },
    }
    // Message Chains: Accessing user.Address.ZipCode.Code creates a chain of method calls,
    // indicating a lack of clear abstraction and making the code harder to maintain.
    fmt.Println(user.Address.ZipCode.Code)
}

The chain user.Address.ZipCode.Code illustrates this problem.

To simplify, encapsulate the access within methods:

package main

import "fmt"

type ZipCode struct {
    Code string
}

type Address struct {
    ZipCode ZipCode
}

func (a Address) GetPostalCode() string {
    return a.ZipCode.Code
}

type User struct {
    Address Address
}

func (u User) GetUserPostalCode() string {
    return u.Address.GetPostalCode()
}

func main() {
    user := User{
        Address: Address{
            ZipCode: ZipCode{Code: "90210"},
        },
    }
    fmt.Println(user.GetUserPostalCode())
}

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

Middle Man

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

package main

import "fmt"

type Service struct{}

func (s Service) PerformAction() {
    fmt.Println("Action performed")
}

type Controller struct {
    Service Service
}

func (c Controller) Execute() {
    // Middle Man: The Controller struct primarily delegates its behavior to the Service struct without adding functionality,
    // making it an unnecessary intermediary that can be removed to simplify the code design.
    c.Service.PerformAction()
}

func main() {
    controller := Controller{
        Service: Service{},
    }
    controller.Execute()
}

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

To refactor, simplify delegation or reassign responsibilities:

package main

import "fmt"

type Service struct{}

func (s Service) PerformAction() {
    fmt.Println("Action performed")
}

func main() {
    service := Service{}
    service.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 struct 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