Skip to the workspace
Pebellslearn by building
Programming Paradigms  ›  Capstone Project

Object-Oriented Programming

Object Oriented Programming 14 minObject-oriented programming bundles data together with the behaviour that is allowed to change it, and real programs mix it with structured and functional code.

software design architecture / Object-Oriented Programming

Explore each scene at your own pace.

01 · The rule

The rule

Object-Oriented Programming

In early Shelfwise, an order was a plain dictionary, and any function could write order["status"] = "cancelled", even for an order that had already shipped. Nothing stopped it, because the rule "you cannot cancel a shipped order" lived in a wiki page, not in the code. Object-oriented programming puts that rule next to the data it protects.

The rule

Bundle data with the behaviour allowed to change it.

An object holds some state (its data) and offers methods (its behaviour). A class is the blueprint; each object made from it is an instance with its own state.

class Order:
    def __init__(self, lines):
        self._lines = lines
        self._status = "placed"

    def ship(self):
        self._status = "shipped"

    def cancel(self):
        if self._status == "shipped":
            raise ValueError("A shipped order cannot be cancelled")
        self._status = "cancelled"

Code outside no longer edits status directly; it asks the order to cancel(), and the order decides whether that is allowed. Calling a method is often described as sending a message: you say what you want, and the object handles how.

A good way to find the objects in a program is to listen to how people describe the business. The nouns they keep using — order, customer, book, invoice — are usually your classes, and the verbs they attach to them are usually the methods.

Objects suit things with identity and a lifecycle: an order that is placed, paid, shipped and delivered; a customer whose address changes; a gift card whose balance goes down.

Paradigms mix. Python, Java, C#, JavaScript and Kotlin all let you use several at once, and good code does:

  • Objects for things with identity, state and rules.
  • Pure functions for calculations.
  • Structured blocks inside every method.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.