Rules an object always keeps
After this: Name an invariant and check it at every method that changes the data.
On this page · 5 sections · 3 checks
The account's fields are private now (lesson 2), and outside code reads the balance through a getter (lesson 3). So every change has to come through one of the account's own methods. This lesson writes the checks inside those methods, and with them the class finally keeps its rule on its own.
A rule that is always true
"The balance is never below zero" is a rule about the account that should hold at every moment anyone can look: right after the account is made, and after every method call. A rule of that kind is called an . A thermostat whose target stays between 10 and 30 has one; so does a list of exam marks where every mark is between 0 and 100.
To keep an invariant, look for every door through which the data can change, and put a check at each door before the change happens. The account has three doors:
| Door | It refuses when | Message |
|---|---|---|
| the constructor | the opening balance is below 0 | opening balance cannot be negative |
deposit | the amount is 0 or less | amount must be positive |
withdraw | the amount is 0 or less, or more than the balance | amount must be positive, not enough money |
Why does deposit need a check? Because deposit(-500) would take 500 out with no test at all. Every door needs its own check, even the ones that look harmless.
Watch one guard
Here is a shorter account to step through. Its withdraw answers Truetrue or Falsefalse instead of refusing with an error, so you can watch the if decide. The band shows the private field inside the account's box, so you can see when it changes. The task asks you to watch the if line on two calls.
- Run the programRun it and step through. withdraw is called twice: first with 30, then with 500. Each time, watch the if line at the top of withdraw, note which line runs next, and watch the balance field in the account's box.
class BankAccount: def __init__(self, opening): self._balance = opening
@property def balance(self): return self._balance
def withdraw(self, amount): if amount > self._balance: return False self._balance = self._balance - amount return True
a = BankAccount(100)print(a.withdraw(30))print(a.withdraw(500))print(a.balance)run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
withdraw(30): is 30 more than 100? No, so the method goes on, takes 30 away and returns Truetrue. In the box, _balancebalance changes from 100 to 70.withdraw(500): is 500 more than 70? Yes, so the method returns Falsefalse at once. The line that changes the balance never runs, and _balancebalance stays 70.- The last line reads the balance:
70.
The whole class
The full account refuses with an error instead. A method can start an error itself: raise ValueError("not enough money")throw new IllegalArgumentException("not enough money"); stops the method at once and hands the error, with its message, to the code that called it. ValueError and IllegalArgumentException are the usual kinds for a bad value passed in. The caller can catch the error with try, as in the Errors and debugging tutorial. Why an error rather than Falsefalse? A caller can forget to look at a returned value and carry on as if the money had been taken. An error stops the program unless the caller catches it on purpose, as this program does with try and excepttry and catch.
Read the output line by line:
- Ana opens with 100 and deposits 50:
150. withdraw(200): 200 is more than 150, so the call is refused. The balance is still150.withdraw(150): 150 is not more than 150, so it is allowed, and the balance is0. Zero keeps the rule, which only forbids going below zero.deposit(-10)is refused: the amount must be positive.BankAccount("Ben", -5)is refused by the constructor, and no account is made.- The history is
[100, 50, -150]. The refused calls left no trace, because each method checks before it changes anything.
Each method follows the same shape: check first, change second. If a check fails, the method stops before the first change, so the object is never left half changed. Try it: change withdraw(150) to withdraw(151) and run again. That call is not inside a try, so the refusal stops the program, and the error message names the rule it broke: not enough money.
Check yourself
Ana's account opens with 100. The program runs deposit(50), then withdraw(200), then withdraw(150), and reads the balance after each call. Which three balances does it see?
Here is withdraw from the guarded account. Which line is the one that keeps the balance from going below zero?
def withdraw(self, amount): if amount <= 0: raise ValueError("amount must be positive") if amount > self._balance: raise ValueError("not enough money") self._balance = self._balance - amount self._history.append(-amount) void withdraw(int amount) { if (amount <= 0) { throw new IllegalArgumentException("amount must be positive"); } if (amount > balance) { throw new IllegalArgumentException("not enough money"); } balance = balance - amount; history.add(-amount); }Complete the test in withdraw that refuses an amount larger than the balance, so that withdraw(500) from 100 is refused and the program prints the refusal and then 70.
class BankAccount: def __init__(self, owner, opening): if opening < 0: raise ValueError("opening balance cannot be negative") self._owner = owner self._balance = opening self._history = [opening]
@property def balance(self): return self._balance
def deposit(self, amount): if amount <= 0: raise ValueError("amount must be positive") self._balance = self._balance + amount self._history.append(amount)
def withdraw(self, amount): if amount <= 0: raise ValueError("amount must be positive") ______________ # ← refuse when it is too much raise ValueError("not enough money") self._balance = self._balance - amount self._history.append(-amount)
def history(self): return list(self._history)
a = BankAccount("Ana", 100)try: a.withdraw(500)except ValueError as e: print("refused:", e)a.withdraw(30)print(a.balance)import java.util.ArrayList;import java.util.List;
class BankAccount { private String owner; private int balance; private List<Integer> history = new ArrayList<>();
BankAccount(String owner, int opening) { if (opening < 0) { throw new IllegalArgumentException("opening balance cannot be negative"); } this.owner = owner; this.balance = opening; history.add(opening); }
int getBalance() { return balance; }
void deposit(int amount) { if (amount <= 0) { throw new IllegalArgumentException("amount must be positive"); } balance = balance + amount; history.add(amount); }
void withdraw(int amount) { if (amount <= 0) { throw new IllegalArgumentException("amount must be positive"); } ______________ // ← refuse when it is too much throw new IllegalArgumentException("not enough money"); } balance = balance - amount; history.add(-amount); }
List<Integer> history() { return new ArrayList<>(history); }}
public class Main { public static void main(String[] args) { BankAccount a = new BankAccount("Ana", 100); try { a.withdraw(500); } catch (IllegalArgumentException e) { System.out.println("refused: " + e.getMessage()); } a.withdraw(30); System.out.println(a.getBalance()); }}Honesty notes
- Say what an invariant is: a rule about an object's data that holds after the constructor and after every method call.
- Find every door through which the data can change, the constructor included, and put a check at each one.
- Write each changing method as check first, change second, so that a refused call leaves the object exactly as it was.
- Say why a method refuses with an error (ValueError in Python, IllegalArgumentException in Java) rather than a returned false: a caller cannot ignore it by accident.