search
HomeBackend DevelopmentGolangPrincípios SOLID em GoLang - Single Responsability Principle (SRP)

In the world of software development, SOLID principles tell us how to organize functions and data so that our codes:

  • Tolerate changes
  • Be easy to understand
  • Be the basis of components that can be used in many software systems

The term SOLID is an acronym for five design postulates, described below:

(S) Single Responsibility Principle: "A module must have one, and only one reason to change"
(The) Open/Closed Principle: "A software artifact must be open for extension but closed for modification"
(L) Liskov Substitution Principle: "A derived class must be replaceable by its base class"
(I) Interface Segregation Principle: "A class should not be forced to implement interfaces and methods that it will not use"
(D) Dependency Inversion Principle: "Depend on abstractions and not implementations"

SOLID and GoLang

Princípios SOLID em GoLang - Single Responsability Principle (SRP)

SOLID is designed for object-oriented programming, and it is known that GoLang is not a language that adopts this paradigm. However, we can use the resources it makes available to meet the OOP methodology. For example, Go does not have inheritance support, but the idea can be compensated with its composition support. Similarly, a type of polymorphism can be created using interfaces.

In this article, the first in a series of 5, I intend to detail the first principle with examples that are close to situations we encounter on a daily basis.

Single Responsibility Principle (SRP)

We already know what the term means, now it's time to learn how to implement it in GoLang.
In this language, we could define this principle as “A function or type must have one and only one job, and one and only one responsibility”, let’s see the following code:

Above, we have a struct we call userService. It has two properties: db, which is responsible for communicating with a relational database, and amqpChannel

, which enables communication with the RabbitMQ messaging service.


UserService implements a method called Create. Within this method we store the received user information in the database and then publish the data to RabbitMQ.

It can be seen that the responsibility of the Create method in the userService is not just one, but two: storing information in the database and publishing a message in a RabbitMQ queue.

This can lead to several problems such as:
  • Difficult to maintain: if one of the requirements changes, such as the way user data is serialized, you will have to modify the logic of the Create method, even if this has nothing to do with your main responsibility , which is to save the data in the database.
  • Test difficulty: as the Create method has two different responsibilities, you will have to create tests for each of them, which can be difficult and laborious.
  • Unnecessary coupling: the logic of publishing user data to a RabbitMQ queue is completely independent of the logic of saving this data to a database. Mixing these two responsibilities in the same method creates unnecessary coupling.

In the following code, we modified the structure to respect the SRP. Check it out:

Note that we have separated the responsibilities into three distinct parts: the repository UserRepository to persist the user to the database, the publisher UserPublisher to send a message to RabbitMQ, and the service UserService that orchestrates these two operations.

In this way, each component is responsible for a specific and independent task, facilitating the maintenance and evolution of the code, in addition to allowing each of these parts to be replaced or improved without affecting the others. For example, if it is necessary to change the database used, simply replace the repository. If it is necessary to change the form of communication, simply change the publisher.

It is worth noting that there is a subtle difference between performing two distinct tasks and delegating their execution. In the original userService.Create example, two operations were performed in one place, violating the principle of single responsibility. After refactoring, we delegated executions to different structs and the Create method was only responsible for coordinating this flow.

To apply SRP in this example, we also ended up implementing some of the other SOLID principles:

  • The Interface Segregation Principle (ISP): each interface represents a single responsibility. Both UserRepository and UserPublisher are interfaces that have only one method, each representing a single responsibility.
  • The Dependency Inversion Principle (DIP): the userService struct depends on abstractions (interfaces) and not on concrete implementations, that is, it does not know the specific implementation of the UserRepository and UserPublisher, only the interfaces that they implement.
  • The Open/Closed Principle (OCP): the code is open for extension, as new repositories or publishers can be easily added without modifying userService.

In the next articles in this series I will provide a more detailed explanation of each of them, with specific examples.

See you later, guys!

References:
SOLID: The First 5 Principles of Object Oriented Design
Clean Coder Blog - The Single Responsibility Principle

The above is the detailed content of Princípios SOLID em GoLang - Single Responsability Principle (SRP). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Go language pack import: What is the difference between underscore and without underscore?Go language pack import: What is the difference between underscore and without underscore?Mar 03, 2025 pm 05:17 PM

This article explains Go's package import mechanisms: named imports (e.g., import "fmt") and blank imports (e.g., import _ "fmt"). Named imports make package contents accessible, while blank imports only execute t

How to implement short-term information transfer between pages in the Beego framework?How to implement short-term information transfer between pages in the Beego framework?Mar 03, 2025 pm 05:22 PM

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

How to convert MySQL query result List into a custom structure slice in Go language?How to convert MySQL query result List into a custom structure slice in Go language?Mar 03, 2025 pm 05:18 PM

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

How do I write mock objects and stubs for testing in Go?How do I write mock objects and stubs for testing in Go?Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How can I define custom type constraints for generics in Go?How can I define custom type constraints for generics in Go?Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

How to write files in Go language conveniently?How to write files in Go language conveniently?Mar 03, 2025 pm 05:15 PM

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

How do you write unit tests in Go?How do you write unit tests in Go?Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How can I use tracing tools to understand the execution flow of my Go applications?How can I use tracing tools to understand the execution flow of my Go applications?Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version