SOLID

Principle
Description

Single responsibility principle

“A class/function/type should have one, and only one reason to change”

Open-Closed principle

“A class should be open for extension but closed for modifications”

Liskov substitution principle

“Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program”

Interface segregation principle

“Clients should not be forced to depend on methods they don't use”

Dependency inversion

“High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should not depend on abstractions”

Single responsibility principle

Before - breaks SRP because the function area will have to be changed for two reasons, the formula of area changes, and second the output of the program changes

package main

import (
	"fmt"
	"math"
)

type circle struct {
	radius float64
}

func (c circle) area() {
	// violating Single Responsibility Principle
	fmt.Printf("circle area: %f\n", math.Pi*c.radius*c.radius)
}

func main() {
	c := circle{
		radius: 3,
	}
	c.area()

}

After - only have to change the function area when the formula changes and the function print when the printing format changes.

Open-Closed principle

In go, this can be achieved by using interfaces and polymorphism => all structs are open for extension but not for modification

Liskov substitution principle

A derived class should be able to substitute its base class without affecting the functionality of the program. e.g. calculateArea can take any subtype of Shape - Square/ Rectangle and its behvaiour won't change.

Interface segregation principle

In Golang, this can be achieved by creating smaller, focused interfaces that provide only the functionality needed by a specific client.

Dependency Inversion Principle

In this example, the Service struct depends on the Database interface, and the MySQL and PostgreSQL structs implement the Database interface. This means that the Service struct can store data in either a MySQL or PostgreSQL database, without having to know or care which database it’s using.

This is an example of the Dependency Inversion Principle in action. The high-level Service module depends on an abstraction (the Database interface), while both the low-level MySQL and PostgreSQL modules depend on the same abstraction. This allows the Service module to be decoupled from the specific implementation of the database, making it more flexible and maintainable.

Last updated

Was this helpful?