Home > Backend Development > Golang > Golang - How a Chef and Waiter Teach the Single Responsibility Principle

Golang - How a Chef and Waiter Teach the Single Responsibility Principle

Barbara Streisand
Release: 2025-01-16 12:21:59
Original
479 people have browsed it

Welcome to the first installment of my SOLID principles series focused on Golang! This series will dissect each SOLID design principle, guiding you toward creating more maintainable and scalable Go applications. We begin with the Single Responsibility Principle (SRP) – a cornerstone concept emphasizing cleaner code by ensuring each module handles a single task. ?


?️ Understanding the Single Responsibility Principle

The Single Responsibility Principle dictates:

A class, module, or function should have only one reason to change.

Essentially, each component should concentrate on a single responsibility. Multi-tasking code becomes difficult to maintain and expand without introducing errors. Adhering to SRP improves modularity, reusability, and testability.

Golang - How a Chef and Waiter Teach the Single Responsibility Principle

?‍? A Real-World SRP Example: The Chef and the Waiter

Consider a busy restaurant. Two key roles ensure customer satisfaction:

  • The Chef: Focuses solely on food preparation.
  • The Waiter: Manages orders, serves food, and addresses customer needs.

Imagine one person performing both roles. The chef pausing cooking to take orders would:

  • Slow service.
  • Delay food preparation.
  • Increase error potential.

This scenario is inefficient; one person juggling unrelated tasks leads to chaos.

Applying SRP in the Restaurant Setting

Following the Single Responsibility Principle:

  • The Chef solely prepares food.
  • The Waiter solely manages orders and customer service.

This separation allows each individual to excel in their specific role, resulting in a more efficient and positive dining experience. ?✨

? SRP in Software Development

Similar to the restaurant example, your code should structure classes and functions to handle only one responsibility. This enhances maintainability, accelerates changes, and minimizes errors.

SRP in Action with Golang

Let's examine how violating SRP can create brittle and unmanageable code.

❌ Example: Violating SRP

Consider a basic coffee shop order management system:

<code>package main

import "fmt"

// Order stores coffee order details.
type Order struct {
    CustomerName string
    CoffeeType   string
    Price        float64
}

// ProcessOrder handles multiple responsibilities.
func (o *Order) ProcessOrder() {
    // Handles payment processing
    fmt.Printf("Processing payment of $%.2f for %s\n", o.Price, o.CustomerName)

    // Prints receipt
    fmt.Printf("Receipt:\nCustomer: %s\nCoffee: %s\nAmount: $%.2f\n", o.CustomerName, o.CoffeeType, o.Price)
}

func main() {
    order := Order{CustomerName: "John Doe", CoffeeType: "Cappuccino", Price: 4.50}
    order.ProcessOrder()
}</code>
Copy after login
Copy after login

The Order struct handles data storage, payment processing, and receipt printing – a clear SRP violation. Modifying any aspect impacts ProcessOrder, hindering maintainability.

?️ Refactoring to Adhere to SRP

Let's separate responsibilities into distinct components:

<code>package main

import "fmt"

// Order stores coffee order details.
type Order struct {
    CustomerName string
    CoffeeType   string
    Price        float64
}

// ProcessOrder handles multiple responsibilities.
func (o *Order) ProcessOrder() {
    // Handles payment processing
    fmt.Printf("Processing payment of $%.2f for %s\n", o.Price, o.CustomerName)

    // Prints receipt
    fmt.Printf("Receipt:\nCustomer: %s\nCoffee: %s\nAmount: $%.2f\n", o.CustomerName, o.CoffeeType, o.Price)
}

func main() {
    order := Order{CustomerName: "John Doe", CoffeeType: "Cappuccino", Price: 4.50}
    order.ProcessOrder()
}</code>
Copy after login
Copy after login

? Advantages of SRP

  • Separation of Concerns: Order stores data; PaymentProcessor handles payments; ReceiptPrinter generates receipts.
  • Enhanced Testability: PaymentProcessor and ReceiptPrinter can be tested independently.
  • Simplified Maintenance: Receipt formatting changes won't affect payment processing.

❓ When to Apply SRP

Identify violations such as:

  • Functions or structs performing unrelated tasks.
  • Modules mixing concerns (e.g., business logic and I/O).

✨ Conclusion

The Single Responsibility Principle simplifies code understanding, maintenance, and expansion. This is just the start! The next post in this series explores the "O" in SOLID: the Open/Closed Principle.

You can also explore my previous post on Dependency Injection, a crucial OOP technique.

Happy coding! ?


Follow me for updates on future posts:

  • Linkedin
  • Github
  • Twitter/X

The above is the detailed content of Golang - How a Chef and Waiter Teach the Single Responsibility Principle. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template