Boss lesson · Unit 06
A bank
Accounts and transfers where every rule is a method that can say no.
What you practise
- Accounts, transfers and a history, rules enforced by methods that return errors
- A first design reviewed and improved
Try a question from this lesson
Pick one
First design for a bank: an account is a struct, and code changes the balance directly. Ada has 100 and takes out 500. What prints?
type Account struct {
Owner string
Balance int
}
a := Account{Owner: "Ada", Balance: 100}
a.Balance -= 500
fmt.Println(a.Balance)Correct answer
-400: nothing stops it
Why
A field is just a variable, and Go will happily subtract 500 from 100. Rules such as "never below zero" do not exist until your code enforces them. In this lesson every rule moves into a method.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The plan
Data: an Account struct with an owner and a balance.
Rules: every change goes through a method with a pointer receiver. The method checks first and changes second, and returns an error when the answer is no.
One named error, ErrFunds, lets callers test for "not enough money" with errors.Is, however much context has been wrapped around it.
var ErrFunds = errors.New(
"insufficient funds")
func (a *Account) Withdraw(n int) error {
if n > a.Balance {
return ErrFunds // check first
}
a.Balance -= n // change second
return nil
}Concept
A history
A bank must be able to say what happened to an account. Give the struct a slice, and let every method that changes the balance add a line to it.
Because the methods are the only way in, the history cannot miss a change. That is the second pay-off of keeping all changes inside methods.
type Account struct {
Balance int
Log []string
}
func (a *Account) Deposit(n int) {
a.Balance += n
a.Log = append(a.Log, "deposit")
}
a := Account{}
a.Deposit(5)
fmt.Println(a.Balance, a.Log)
// 5 [deposit]10 more exercises in the app
- 1× fill the blanks
- 4× type the answer
- 3× multiple choice
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.