I wrote it in Go to understand the SOLID principle

About the SOLID principle

What is the SOLID principle?

--SRP (single responsibility principle) --OCP (Open and Closed Principles) --LSP (Liskov Substitution Principle) --ISP (Principle of interface separation) --DIP (Principle of Dependency Reversal)

It is an acronym for.

Why SOLID Principles?

The reason for applying SOLID is

――Resistant to change --Easy to understand --Available in many software systems

Can be mentioned. From the following, I will touch on the explanation of each principle and the code.

About each principle of SOLID

SRP (single responsibility principle)

Explanation

The principle that there should be no multiple reasons when changing a module, class, function, etc. The reason is to prevent the following events from occurring

--Merges and conflicts occur when multiple people modify one source file --The changes are affected by unexpected things

code

bad example

One interface has multiple responsibilities for managing employees, storing employee data.


type EmployeeWorkManage interface {
	calculatePay()
	reportHours()
	saveEmployee()
}

After improvement

Create separate interfaces for managing employees and storing employee data so that each has one responsibility.


type EmployeeWorkManage interface {
	calculatePay()
	reportHours()
}

type EmployeeDataManage interface {
	saveEmployee()
}

OCP (Open and Closed Principles)

Explanation

The principle that it must be open for software extensions and closed for modifications That way you can scale your system unaffected by changes.

code

By creating an interface called Animal and creating a Dog type or Cat type method depending on it, you can execute the bark method without worrying about the Dog type or Cat type in the main process. Also, if you want to create a new Bird, you only need to add it by making it dependent on the Animal interface.


package main
import(
	"fmt"
)

type Animal interface {
	bark()
	eat()
}

type Dog struct {}

type Cat struct {}

func (d Dog) bark(){
	fmt.Println("Bow-wow")
}

func (d Dog) eat(){
	fmt.Println("Bakubaku")
}

func (c Cat) bark(){
	fmt.Println("Meow")
}

func (c Cat) eat(){
	fmt.Println("Mushamsha")
}

func main(){
	dog := Dog{}
	cat := Cat{}

	animals := []Animal{dog, cat}
	
	for _, animal := range animals {
		animal.bark()
	}

}

LSP (Liskov Substitution Principle)

Explanation

S type object: o1 T-type object: o2 The principle that S is a derivative of T if, at some point, the behavior of P does not change when using o1 instead of o2 for program P defined using T.

code

Since Go has no inheritance, it does not violate the Liskov Substitution Principle and is not conscious (?)

ISP (Principle of Interface Separation)

Explanation

The principle of not forcing you to rely on unnecessary interfaces Group only relevant interfaces and lose the dependency of unused methods.

code

bad example

If you try to create a humanoid from the Animal Interface as shown below, you will have to describe the fly method that you do not use.


type AnimalInterface interface {
	fly()
	run()
	swim()
}

After improvement

Separate the interface from Bird Interface for birds and Human Interface for humans. By doing so, you don't have to write unnecessary methods.

type BirdInterface interface {
	fly()
}

type HumanInterface interface {
	run()
	swim()
}

type Bird struct {}
type Human struct{}

func (b Bird) fly(){
	fmt.Println("Fly! !!")
}

func (h Human) run(){
	fmt.Println("I'll run ~")
}

func (h Human) swim(){
	fmt.Println("Swimming~")
}

func main(){
	bird := Bird{}
	human := Human{}

	bird.fly()
	human.run()
}

DIP (Dependency Reversal Principle)

Explanation

The principle of not relying on concrete modules that are frequently changed (modules in which the implementation of a function is written) Avoid reliance on modifiable concreteness and rely on a stable abstract interface. Use the Abstract Factory pattern to refer to the abstract interface.

code

By relying on the Abstract Factory, the dependency destination becomes an image as shown in the figure, and the user's data can be acquired without worrying about either DB or text.

Untitled Diagram.png


package main
import(
	"fmt"
)

type User struct {
	id int
	name string
}

type AbstractFactory interface {
	getData() User
}

type DbManage struct {}

func (db DbManage) getData() User {
	return User{1, "DB TARO"}
}

type TextManage struct {}

func (text TextManage) getData() User {
	return User{2, "TEXT JIRO"}
}

func getUserData(manageType string) User {
	var manageFactry AbstractFactory
	switch manageType {
	case "DB":
		manageFactry = DbManage{}
		return manageFactry.getData()
	case "TEXT":
		manageFactry = TextManage{}
		return manageFactry.getData()
	default:
		return User{3, "Anonymous"}
	}
}

func main(){
	user := getUserData("DB")
	fmt.Println(user.id, user.name)
}



reference

https://labs.septeni.co.jp/entry/2017/02/21/164127 https://maroyaka.hateblo.jp/entry/2017/05/22/165355 https://qiita.com/shunp/items/646c86bb3cc149f7cff9 https://golangvedu.wordpress.com/2017/01/31/golang-design-pattern-abstract-factory-and-factory-method/

Finally

Somehow, I feel like I understand the SOLID principle. If you have any questions or suggestions, we would appreciate it if you could write them in the comments.

Recommended Posts

I wrote it in Go to understand the SOLID principle
I wrote the hexagonal architecture in go language
I wrote you to watch the signal with Go
Note that I understand the least squares algorithm. And I wrote it in Python.
I wrote the queue in Python
I wrote the stack in Python
I wrote the code to write the code of Brainf * ck in python
I wrote the selection sort in C
I wrote the sliding wing in creation.
For the first time in Numpy, I will update it from time to time
Note that I understand the algorithm of the machine learning naive Bayes classifier. And I wrote it in Python.
I wrote "Introduction to Effect Verification" in Python
I want to display the progress in Python!
I didn't understand the Resize of TensorFlow so I tried to summarize it visually.
I referred to it when I got stuck in the django geodjango tutorial (editing)
I tried to graph the packages installed in Python
I want to fully understand the basics of Bokeh
I want to write in Python! (3) Utilize the mock
I was able to repeat it in Python: lambda
I want to use the R dataset in python
I want to replace the variables in the python template file and mass-produce it in another file.
What I did when I was angry to put it in with the enable-shared option
[Introduction] I tried to implement it by myself while explaining to understand the binary tree
I wrote a CLI tool in Go language to view Qiita's tag feed with CLI
I tried to understand it carefully while implementing the algorithm Adaboost in machine learning (+ I deepened my understanding of array calculation)
I wrote the basic operation of Seaborn in Jupyter Lab
I tried to summarize the code often used in Pandas
I tried to illustrate the time and time in C language
PyTorch's book was difficult to understand, so I supplemented it
To write a test in Go, first design the interface
I wrote a script to get a popular site in Japan
I tried to summarize the commands often used in business
I tried to implement the mail sending function in Python
I can't log in to the admin page with Django3
I wrote a script to combine the divided ts files
I wrote the basic operation of Numpy in Jupyter Lab.
I want to make the Dictionary type in the List unique
I understand Python in Japanese!
I want to align the significant figures in the Numpy array
I want to know the legend of the IT technology world
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
The story I was addicted to when I specified nil as a function argument in Go
I wrote a script that splits the image in two
I didn't want to write the AWS key in the program
Scraping the list of Go To EAT member stores in Fukuoka prefecture and converting it to CSV
I couldn't understand Fence Repair of the ant book easily, so I will follow it in detail.
Part 1 I wrote the answer to the reference problem of how to write offline in real time in Python
Scraping the list of Go To EAT member stores in Niigata prefecture and converting it to CSV
I tried to describe the traffic in real time with WebSocket
[Linux] I want to know the date when the user logged in
I wrote Django commands to make it easier to debug Celery tasks
I tried to process the image in "sketch style" with OpenCV
I wrote a function to load a Git extension script in Python
LINEbot development, I want to check the operation in the local environment
I wrote a script to extract a web page link in Python
I want to create a pipfile and reflect it in docker
I tried to process the image in "pencil style" with OpenCV
I want to make the second line the column name in pandas
I want to pass the G test in one month Day 1
The easiest way to get started in Slack socket mode (Go)
Create a function to get the contents of the database in Go