programmingconcepts

§ 4.1 · Paradigms

Objects and classes

An object bundles data with the functions that work on it; a class is the blueprint for making objects.

Object-oriented programming groups data and the functions that work on it into objects. A class is a blueprint: it defines which fields an object holds and which methods it has. Each object made from it, called an instance, has its own data. Hiding the data behind methods, called encapsulation, keeps the object in a valid state.

Class
A blueprint
Object
One instance made from it
Fields
The data each object holds
Methods
Functions that belong to the object
Requires
FunctionsVariables and types

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

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

  1. Getters and setters for everything. A setter for every field is a public variable with extra steps. Expose operations, like withdraw, not raw fields.
  2. God objects. One class that does everything is hard to change. Give each class one responsibility.
  3. Forgetting self or this. 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?

Check yourself

Why make the balance private?

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).

Newsletter

One new concept each week, by email.

Signup opens soon.