Upgrade to Pro — share decks privately, control downloads, hide ads and more …

SOLID in Go

syossan27
January 31, 2019

SOLID in Go

syossan27

January 31, 2019
Tweet

More Decks by syossan27

Other Decks in Technology

Transcript

  1. Example package main import "fmt" type Cat struct{} func (c

    Cat) Legs() int { return 4 } func (c Cat) PrintLegs() { fmt.Printf("I have %d legs\n”, c.Legs()) } func main() { var cat Cat cat.PrintLegs() }
  2. Bad Code type Cat struct { Type int // 0:

    Cat, 1:OctCat } func (c Cat) Legs() int { if c.Type == 0 { return 4 } else { return 5 } } func (c Cat) PrintLegs() { fmt.Printf("I have %d legs\n", c.Legs()) } func main() { cat := Cat{Type: 0} cat.PrintLegs() octCat := Cat{Type: 1} octCat.PrintLegs() }
  3. e type Cat struct{ Name string } func (c Cat)

    Legs() int { return 4 } func (c Cat) PrintLegs() { fmt.Printf("I have %d legs\n", c.Legs()) } type OctoCat struct{ Cat } func (o OctoCat) Legs() int { return 5 } func (o OctoCat) PrintLegs() { fmt.Printf("I have %d legs\n", o.Legs()) } func main() { var octo OctoCat var cat Cat fmt.Println(cat.Legs()) // “4” cat.PrintLegs() // “I have 4 legs” fmt.Println(octo.Legs()) // “5” octo.PrintLegs() // “I have 5 legs” }
  4. type FelidaeInterface interface { Legs() int PrintLegs() } type Felidae

    struct { Name string FelidaeInterface } type Cat struct{} func (c Cat) Legs() int { return 4 } func (c Cat) PrintLegs() { fmt.Printf("I have %d legs\n", c.Legs()) } type OctoCat struct{} func (o OctoCat) Legs() int { return 5 } func (o OctoCat) PrintLegs() { fmt.Printf("I have %d legs\n", o.Legs()) } func main() { cat := Felidae{FelidaeInterface: Cat{}} octo:= Felidae{FelidaeInterface: OctoCat{}} fmt.Println(cat.Legs()) cat.PrintLegs() fmt.Println(octo.Legs()) octo.PrintLegs() }
  5. type A struct { } func (a A) Test() {

    fmt.Println("Printing A") } type B struct { A } func ImpossibleLiskovSubstitution(a A) { a.Test() } func main() { a := B{} ImpossibleLiskovSubstitution(a) // Aͱͯ͠ৼΔ෣͑ͣɺΤϥʔͱͳΔͨΊLSPҧ൓͍ͯ͠Δ } Bad Code
  6. type A struct { } type tester interface { Test()

    } func (a A) Test() { fmt.Println("Printing A") } type B struct { A } func PossibleLiskovSubstitution(a tester) { a.Test() } func main() { a := B{} PossibleLiskovSubstitution(a) } Good Code