refactor: inteface composition

This commit is contained in:
Inanc Gumus
2019-08-27 15:21:17 +03:00
parent 5d7047a66f
commit aff765c4a8
12 changed files with 151 additions and 146 deletions

View File

@ -7,19 +7,35 @@
package main package main
import "fmt" import (
"fmt"
"strconv"
"time"
)
type book struct { type book struct {
title string *product
price money published interface{}
readTime int
} }
func (b book) print() { func (b *book) String() string {
fmt.Printf("%-15s: %s\n", b.title, b.price.string()) p := format(b.published)
return fmt.Sprintf("%s - (%v)", b.product, p)
} }
// TODO: NEW func format(v interface{}) string {
func (b book) sum() money { var t int
return b.price
switch v := v.(type) {
case int:
t = v
case string:
t, _ = strconv.Atoi(v)
default:
return "unknown"
}
const layout = "2006/01"
u := time.Unix(int64(t), 0)
return u.Format(layout)
} }

View File

@ -1,17 +0,0 @@
package main
// usually: include the discount method in the list.go
// it is here for clarity
// TODO: NEW
func (l list) discount(ratio float64) {
type discounter interface {
discount(float64)
}
for _, it := range l {
if it, ok := it.(discounter); ok {
it.discount(ratio)
}
}
}

View File

@ -7,27 +7,6 @@
package main package main
import "fmt"
type game struct { type game struct {
title string *product
price money
playTime int
}
func (g *game) print() {
fmt.Printf("%-15s: %s\n", g.title, g.price.string())
}
// func (g *game) String() string {
// return fmt.Sprintf("%-15s: $%.2f", g.title, g.price)
// }
func (g *game) discount(ratio float64) {
g.price *= money(1 - ratio)
}
// TODO: NEW
func (g *game) sum() money {
return g.price
} }

View File

@ -7,28 +7,51 @@
package main package main
import "fmt" import (
"fmt"
"strings"
)
type summer interface {
sum() money
}
type item interface {
summer // same as: `sum() money`
fmt.Stringer // same as: `String() string`
}
type list []item type list []item
func (l list) print() { func (l list) String() string {
if len(l) == 0 { if len(l) == 0 {
fmt.Println("Sorry. Our store is closed. We're waiting for the delivery 🚚.") return "Sorry. We're waiting for delivery 🚚."
return }
var str strings.Builder
for _, it := range l {
fmt.Fprintf(&str, "%s\n", it)
}
fmt.Fprintf(&str, "\tTOTAL : $%.2f", l.sum())
return str.String()
}
func (l list) sum() (total money) {
for _, it := range l {
total += it.sum()
}
return
}
func (l list) discount(ratio float64) {
type discounter interface {
discount(float64)
} }
for _, it := range l { for _, it := range l {
it.print() if it, ok := it.(discounter); ok {
it.discount(ratio)
}
} }
// TODO: NEW
fmt.Printf("\tTOTAL : $%.2f\n", l.sum())
}
// TODO: NEW
func (l list) sum() (n money) {
for _, it := range l {
n += it.sum()
}
return n
} }

View File

@ -7,37 +7,36 @@
package main package main
// import "fmt" import (
"fmt"
"sort"
)
func main() { func main() {
var ( store := list{
mobydick = book{title: "moby dick", price: 10, readTime: 10} &book{&product{"moby dick", 10}, 118281600},
minecraft = game{title: "minecraft", price: 20, playTime: 5} &book{&product{"odyssey", 15}, "733622400"},
tetris = game{title: "tetris", price: 5, playTime: 2} &book{&product{"hobbit", 25}, nil},
rubik = puzzle{title: "rubik's cube", price: 5} &puzzle{&product{"rubik's cube", 5}},
) &game{&product{"minecraft", 20}},
&game{&product{"tetris", 5}},
&toy{&product{"yoda", 150}},
}
var store list books := store[:3]
store = append(store, &minecraft, &tetris, mobydick, rubik) others := store[3:]
// tetris.discount(.8)
// store.print()
store.discount(.5) books.discount(.5)
store.print() fmt.Printf("%s\n", store)
// t := store.time() sort.Sort(byPrice(others))
// fmt.Printf("Total entertainment time: %d hours\n", t) fmt.Printf("\n%s\n", store)
// games := store[:2] store = list{books, others}
// other := store[2:] fmt.Printf("\n%s\n", store)
// games.print()
// other.print()
// list{games, other}.print()
// var b *book // store.discount(.5)
// // sort.Sort(sort.Reverse(byPrice(store)))
// var np printer // sort.Sort(byName(store))
// np = b // fmt.Println(store)
// // p := printer(puzzle{title: "sidewinder", price: 10})
// fmt.Println(np == nil)
} }

View File

@ -11,6 +11,6 @@ import "fmt"
type money float64 type money float64
func (m money) string() string { func (m money) String() string {
return fmt.Sprintf("$%.2f", m) return fmt.Sprintf("$%.2f", m)
} }

View File

@ -0,0 +1,27 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import "fmt"
type product struct {
title string
price money
}
func (p *product) discount(ratio float64) {
p.price *= money(1 - ratio)
}
func (p *product) sum() money {
return p.price
}
func (p *product) String() string {
return fmt.Sprintf("%-15s: %s", p.title, p.price)
}

View File

@ -7,18 +7,6 @@
package main package main
import "fmt"
type puzzle struct { type puzzle struct {
title string *product
price money
}
func (p puzzle) print() {
fmt.Printf("%-15s: %s\n", p.title, p.price.string())
}
// TODO: NEW
func (p puzzle) sum() money {
return p.price
} }

View File

@ -0,0 +1,20 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
type byPrice list
func (l byPrice) Less(i, j int) bool { return l[i].sum() < l[j].sum() }
func (l byPrice) Len() int { return len(l) }
func (l byPrice) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
type byName list
func (l byName) Less(i, j int) bool { return l[i].String() < l[j].String() }
func (l byName) Len() int { return len(l) }
func (l byName) Swap(i, j int) { l[i], l[j] = l[j], l[i] }

View File

@ -1,19 +0,0 @@
package main
// usually: include the time method in the list.go
// it is here for clarity
// TODO: NEW
// you could include a time method in the book and game instead.
// but sometimes it is not possible to do so.
func (l list) time() (total int) {
for _, it := range l {
switch it := it.(type) {
case *game:
total += it.playTime
case book:
total += it.readTime
}
}
return total
}

View File

@ -0,0 +1,12 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
type toy struct {
*product
}

View File

@ -1,23 +0,0 @@
package main
// don't separate your interfaces like this.
// put them in the same file where you need to use them.
// this is here for clarity
type printer interface {
print()
}
// TODO: NEW
type summer interface {
sum() money
}
// TODO: NEW
// interface embedding
// When an interface includes multiple methods,
// choose a name that accurately describes its purpose.
type item interface {
printer
summer
}