SOLID principles with examples in Go

We’ll be using an application that retrieves list of players and equipment for sports as an example.

/*

* main.go

*/

package main



import "fmt"



func main() {

sportName := "ping pong"



var equipmentList []string

if sportName == "basketball" {

equipmentList = []string{

"ball",

"hoop",

}

} else if sportName == "ping pong" {

equipmentList = []string{

"ball",

"paddle",

}

} else if sportName == "soccer" {

equipmentList = []string{

"ball",

"cleats",

}

}



var players []string

if sportName == "basketball" {

players = []string{

"Michael Jordan",

"Shaquille O'Neal",

}

} else if sportName == "ping pong" {

players = []string{

"Ma Long",

"Hugo Calderano",

}

} else if sportName == "soccer" {

players = []string{

"Cristiano Ronaldo",

"Lionel Messi",

}

}



fmt.Println("equipmentList", equipmentList)

fmt.Println("players", players)

}

Let’s refactor the code above as we learn each principle.

Single Responsibility Principle

An object should only do one thing and all its responsibilities should be encapsulated under one class. The outcomes of SRP are flexible design, few if/switch statements, and software entities with strongly related responsibilities (high cohesion) with minimal dependency on other components (low coupling).

Example

The original code has too many things going on in the main method, so let’s create a sport struct to encapsulate the provision of players and equipment.