Why objects
A bank account has data, an owner and a balance, and rules: you can’t withdraw more than you have, and you can’t deposit a negative amount. Without objects, the balance is a variable any code can change, and every place that changes it must remember the rules.
An object keeps the data and the rules together. The only way to change the balance is to call deposit or withdraw, and they enforce the rules every time.
Class, object, instance
- A class describes what every account looks like: its fields and methods.
- An object, or instance, is one actual account, made from the class.
- A constructor (
__init__,constructor,NewBankAccount,new) sets up each new object’s fields.
ada = BankAccount("Ada", 100) # one object
grace = BankAccount("Grace") # another, with its own balance
ada.deposit(50) # changes ada only
class BankAccount:
"""Data (owner, balance) bundled with the methods that may change it."""
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance # the leading _ says "don't touch this from outside"
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self._balance += amount
def withdraw(self, amount):
if amount <= 0 or amount > self._balance:
raise ValueError("invalid amount or insufficient funds")
self._balance -= amount
@property
def balance(self): # read-only from outside
return self._balance// Data (owner, balance) bundled with the methods that may change it.
class BankAccount {
#balance; // private: only code inside the class can read or write it
constructor(owner, balance = 0) {
this.owner = owner;
this.#balance = balance;
}
deposit(amount) {
if (amount <= 0) throw new RangeError('deposit must be positive');
this.#balance += amount;
}
withdraw(amount) {
if (amount <= 0 || amount > this.#balance) throw new RangeError('invalid amount or insufficient funds');
this.#balance -= amount;
}
get balance() { // read-only from outside
return this.#balance;
}
}import "errors"
// BankAccount bundles data with the methods that may change it.
// Go has no classes: a struct plus methods plays the same role.
type BankAccount struct {
Owner string
balance int // lowercase: private to this package
}
func NewBankAccount(owner string, balance int) *BankAccount {
return &BankAccount{Owner: owner, balance: balance}
}
func (a *BankAccount) Deposit(amount int) error {
if amount <= 0 {
return errors.New("deposit must be positive")
}
a.balance += amount
return nil
}
func (a *BankAccount) Withdraw(amount int) error {
if amount <= 0 || amount > a.balance {
return errors.New("invalid amount or insufficient funds")
}
a.balance -= amount
return nil
}
func (a *BankAccount) Balance() int { return a.balance } // read-only from outside// Bundles data with the methods that may change it. Rust has no classes:
// a struct plus an impl block plays the same role.
pub struct BankAccount {
pub owner: String,
balance: u64, // not pub: private to this module
}
impl BankAccount {
pub fn new(owner: &str, balance: u64) -> Self {
BankAccount { owner: owner.to_string(), balance }
}
pub fn deposit(&mut self, amount: u64) -> Result<(), String> {
if amount == 0 {
return Err("deposit must be positive".to_string());
}
self.balance += amount;
Ok(())
}
pub fn withdraw(&mut self, amount: u64) -> Result<(), String> {
if amount == 0 || amount > self.balance {
return Err("invalid amount or insufficient funds".to_string());
}
self.balance -= amount;
Ok(())
}
pub fn balance(&self) -> u64 {
self.balance // read-only from outside
}
}Encapsulation
The balance is private: code outside the class can read it through balance but can’t assign to it. Each language marks this differently:
| Language | Private | How strict |
|---|---|---|
| Python | Leading underscore, _balance |
A convention; it can still be reached |
| JavaScript | #balance |
Enforced by the language |
| Go | Lowercase name, balance |
Private to the package |
| Rust | No pub |
Private to the module |
Inheritance and composition
A class can inherit from another, taking its fields and methods and adding or changing some: a SavingsAccount that is a BankAccount plus interest. Inheritance is useful, but deep chains of it get rigid, and a change high up ripples everywhere.
The common advice is to prefer composition: give an object other objects as fields, instead of inheriting from them. Go and Rust have no inheritance at all and rely on composition, plus interfaces or traits for shared behaviour. The SOLID principles cover when inheritance goes wrong.
Common mistakes
- Getters and setters for everything. A setter for every field is a public variable with extra steps. Expose operations, like
withdraw, not raw fields. - God objects. One class that does everything is hard to change. Give each class one responsibility.
- Forgetting
selforthis. Inside a method, fields are reached through the object:self._balance, not_balance.
Check yourself
Check yourself
You create two BankAccount objects and deposit into one. What happens to the other's balance?
Each instance has its own fields. Methods act on the object they’re called on, so the other account is untouched.
Check yourself
Why make the balance private?
If outside code can’t set the balance directly, the only way to change it is through deposit and withdraw, which refuse invalid amounts.
Sources
- Bertrand Meyer, Object-Oriented Software Construction, 2nd edition (1997).
- Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns (1994), introduction: “Favor object composition over class inheritance.”
- Alan Kay, “The Early History of Smalltalk,” ACM SIGPLAN Notices 28, no. 3 (1993).
Finished this page?
Your list