Reading without writing
After this: Read a private field through a getter or a property, leave out the setter, and hand out copies.
On this page · 5 sections · 3 checks
In lesson 2 the balance became private, so outside code can no longer change it. But outside code still needs to see it: a cash machine shows your balance on the screen. This lesson lets outside code read a private field without being able to write it.
A method that only reads
The plan is a public method that returns the field's value and changes nothing. Outside code calls it whenever it wants to know the balance. Such a method is called a . In Java it is usually named get plus the field's name: getBalance().
Python has a neater way to write the same thing. Put @property on the line above a method named balance. Outside code then reads a.balance with no brackets, as if it were a field, but Python runs the method each time. That method is a . It is still a method, which is why the class diagram in lesson 2 lists it with the methods, as + balance(): int, even though outside code reads it without brackets. Here are both:
class BankAccount: def __init__(self, owner, opening): self._owner = owner self._balance = opening
@property def balance(self): return self._balance
def deposit(self, amount): self._balance = self._balance + amount
a = BankAccount("Ana", 100)a.deposit(50)print(a.balance)try: a.balance = 999except AttributeError as e: print("AttributeError:", e)150 AttributeError: property 'balance' of 'BankAccount' object has no setter
class BankAccount { private String owner; private int balance;
BankAccount(String owner, int opening) { this.owner = owner; this.balance = opening; }
int getBalance() { return balance; }
void deposit(int amount) { balance = balance + amount; }}
public class Main { public static void main(String[] args) { BankAccount a = new BankAccount("Ana", 100); a.deposit(50); System.out.println(a.getBalance()); // a.setBalance(999); would not compile: there is no such method }}150
Read it in order:
- The fields are private:
_ownerand_balancein Python,privatein Java. - The reading method returns the balance and does nothing else: the property balancegetBalance().
depositchanges the balance from inside the class. Lesson 4 adds its check.- The program deposits 50 and reads the balance from outside:
150. - The last lines try a.balance = 999. A property with no way to set it refuses, and Python raises AttributeError: property 'balance' of 'BankAccount' object has no setter.The commented line, a.setBalance(999), would not compile if you wrote it: the class has no such method, and the compiler says cannot find symbol.
No setter for the balance
The method that would store a new value in a field is called a . The guarded account has none for its balance, on purpose. A setter that stores any value it is given is no safer than an open field: call it with -400 and the account accepts it.
Instead, outside code changes the balance through methods named for what happens in the real world: deposit and withdraw. Each one knows what a sensible change looks like, so each one can check it. A good habit: write a getter when outside code needs to see a value, and a method named for the action when it needs to change one.
A getter can hand out too much
The account also keeps a history: a list with the opening balance and every change after it. Outside code may want to show it, so the class has a method history that returns it. The first version returns the list field itself. Follow this program:
class BankAccount: def __init__(self, opening): self._balance = opening self._history = [opening]
def deposit(self, amount): self._balance = self._balance + amount self._history.append(amount)
def history(self): return self._history
a = BankAccount(100)a.deposit(50)h = a.history()h.append(1000000)print(h)print(a.history())[100, 50, 1000000] [100, 50, 1000000]
import java.util.ArrayList;import java.util.List;
class BankAccount { private int balance; private List<Integer> history = new ArrayList<>();
BankAccount(int opening) { balance = opening; history.add(opening); }
void deposit(int amount) { balance = balance + amount; history.add(amount); }
List<Integer> history() { return history; }}
public class Main { public static void main(String[] args) { BankAccount a = new BankAccount(100); a.deposit(50); List<Integer> h = a.history(); h.add(1000000); System.out.println(h); System.out.println(a.history()); }}[100, 50, 1000000] [100, 50, 1000000]
- The account opens with 100, and
deposit(50)adds a second entry: the list is[100, 50]. h = a.history()gets the list. In both languages, returning a list hands out that very list, not a copy. Nowhand the account hold the same list.- The program adds 1000000 to
h. Because it is the same list, the account's history changes too. - Both prints show
[100, 50, 1000000]. Outside code has changed private data without touching a private field.
The fix is to hand out a copy: a new list with the same numbers. list(self._history)new ArrayList<>(history) makes one.
Now h is a separate list. Adding to it changes only h, and the account's history is still [100, 50]. The same care applies to any field that holds a list, a dictionary or another object: return a copy, or return something that cannot be changed.
Check yourself
A teammate wants to add one more public method to the guarded BankAccount. Which of these should not exist, because it would let outside code break the rule that the balance never goes below zero?
history returns a copy. The program changes what it got back. What does this print?
class BankAccount: def __init__(self, opening): self._balance = opening self._history = [opening]
def deposit(self, amount): self._balance = self._balance + amount self._history.append(amount)
def history(self): return list(self._history)
a = BankAccount(20)a.deposit(5)a.deposit(7)h = a.history()h.append(99)print(a.history())import java.util.ArrayList;import java.util.List;
class BankAccount { private int balance; private List<Integer> history = new ArrayList<>();
BankAccount(int opening) { balance = opening; history.add(opening); }
void deposit(int amount) { 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(20); a.deposit(5); a.deposit(7); List<Integer> h = a.history(); h.add(99); System.out.println(a.history()); }}Complete history so that it returns a new list with the same numbers, and the program prints the account's list unchanged on its second line: [100, 50].
class BankAccount: def __init__(self, opening): self._balance = opening self._history = [opening]
def deposit(self, amount): self._balance = self._balance + amount self._history.append(amount)
def history(self): ______________ # ← return a copy
a = BankAccount(100)a.deposit(50)h = a.history()h.append(1000000)print(h)print(a.history())import java.util.ArrayList;import java.util.List;
class BankAccount { private int balance; private List<Integer> history = new ArrayList<>();
BankAccount(int opening) { balance = opening; history.add(opening); }
void deposit(int amount) { balance = balance + amount; history.add(amount); }
List<Integer> history() { ______________ // ← return a copy }}
public class Main { public static void main(String[] args) { BankAccount a = new BankAccount(100); a.deposit(50); List<Integer> h = a.history(); h.add(1000000); System.out.println(h); System.out.println(a.history()); }}Honesty notes
- Write a getter that returns a private field and changes nothing, such as getBalance in Java.
- Write a Python property with @property, which outside code reads like a field, and say what happens when outside code tries to set one that has no setter.
- Leave out the setter for a value that must follow a rule, and change it through methods named for the action, such as deposit and withdraw.
- Return a copy of a list field, because returning the list itself lets outside code change the object's data.