Skip to content

Instantly share code, notes, and snippets.

@invasionofsmallcubes
Created October 10, 2018 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save invasionofsmallcubes/79c965eda69e71174cf55293e85eed57 to your computer and use it in GitHub Desktop.
Save invasionofsmallcubes/79c965eda69e71174cf55293e85eed57 to your computer and use it in GitHub Desktop.
// goods/base.go
package goods
type base struct {
name string
price float64
exported bool
}
func (good *base) PriceWithTaxes() float64 {
return good.price + good.price*0.1 + good.exportedPrice()
}
func (good *base) Name() string {
return good.name
}
func (good *base) exportedPrice() float64 {
if good.exported {
return good.price * 0.05
} else {
return 0.0
}
}
func NewBaseGood(name string, price float64, exported bool) *base {
return &base{name: name, price: price, exported: exported}
}
// goods/book.go
package goods
type book struct {
*base
}
func (good *book) PriceWithTaxes() float64 {
return good.price + good.exportedPrice()
}
func NewBook(name string, price float64, exported bool) *book {
return &book{base: NewBaseGood(name, price, exported)}
}
// goods/good.go
package goods
type Good interface {
PriceWithTaxes() float64
Name() string
}
// salestaxes.go
package salestaxes
import . "golearn/goods"
type ShoppingCart struct {
Items []Good
}
func (cart *ShoppingCart) AddItem(good Good) {
cart.Items = append(cart.Items, good)
}
func (cart *ShoppingCart) Total() float64 {
result := 0.0
for _, good := range cart.Items {
result += good.PriceWithTaxes()
}
return result
}
// shoppingcartprinter.go
package salestaxes
import "fmt"
func PrintShoppingCart(cart ShoppingCart) {
for _, elem := range cart.Items {
fmt.Printf("%v with cost %g\n", elem.Name(), elem.PriceWithTaxes())
}
fmt.Printf("Total cost is %g\n")
}
// salestaxes_test.go
package salestaxes_test
import (
. "golearn"
. "golearn/goods"
"testing"
)
func TestSalesTaxes(t *testing.T) {
shoppingCart := ShoppingCart{Items: make([]Good, 0)}
shoppingCart.AddItem(NewBaseGood("a good", 12.0, false))
shoppingCart.AddItem(NewBaseGood("another good", 12.0, false))
shoppingCart.AddItem(NewBook("a book", 10.0, true))
expectedResult := 36.9
PrintShoppingCart(shoppingCart)
if shoppingCart.Total() != expectedResult {
t.Errorf("Total is expected to be %g, it was %g",
expectedResult,
shoppingCart.Total())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment