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

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

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

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

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

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

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
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
Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version
