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.
The shortcut
For each part of a feature, ask: does it have identity and changing state with rules? Yes: make it an object. No, it is a calculation: make it a pure function. Either way, the step-by-step logic inside is structured code.
The gift card
It has an identity (its code), a balance that changes, and rules like "never below zero". Object:
GiftCardwithspend()andtop_up().
The trap is making everything an object. A class with no state and one method, such as TaxCalculator().calculate(total), is usually just a function in disguise.
Drills
Answer fast — trust the rule.
What is the relationship between a class and an object?
Why is order.cancel() better than order["status"] = "cancelled"?
Which Shelfwise part is the best fit for an object?
Can one program use structured, functional and object-oriented code together?
Remember
- Bundle data with the behaviour allowed to change it.
- Identity and changing state with rules: an object. A calculation: a pure function.
- Trap: a stateless one-method class is just a function wearing a costume.
