Method Chaining Pattern — ELI5
Imagine you’re at a sandwich shop. Instead of placing three separate orders, you say: “I’d like wheat bread, add turkey, add lettuce, and toast it.”
That’s one sentence that gives multiple instructions in a row. Each instruction builds on the previous one. The sandwich artist doesn’t start over — they keep working on the same sandwich.
Method chaining works the same way in code. Instead of writing three separate lines, you write one flowing line where each command returns the thing you’re working on, so the next command can keep going.
Without Chaining
sandwich.set_bread("wheat")
sandwich.add_topping("turkey")
sandwich.add_topping("lettuce")
sandwich.toast()
Four separate lines, each starting with sandwich.
With Chaining
sandwich.set_bread("wheat").add_topping("turkey").add_topping("lettuce").toast()
One flowing line. Each step returns the sandwich, so the next step can keep building.
How Does It Work?
The trick is simple: after each action, the method says “here, take the sandwich back.” In code, this means the method returns self — the object itself. When the next method in the chain receives the object, it can do its thing and pass it along again.
Where You’ve Seen It
If you’ve used a tool like pandas for data or SQLAlchemy for databases, you’ve probably seen chaining:
results = df.filter(...).sort_by(...).limit(10)
Each step transforms the data and passes it to the next step.
One thing to remember: Method chaining works because each method returns the object itself, letting you stack multiple operations in a single flowing expression.
See Also
- Python Adapter Pattern How Python's Adapter Pattern works like a travel power plug — making incompatible things work together.
- Python Bridge Pattern Why separating what something does from how it does it keeps your Python code from becoming a tangled mess.
- Python Builder Pattern Why building complex Python objects step by step beats cramming everything into one giant constructor.
- Python Composite Pattern How the Composite Pattern lets you treat a group of things the same way you'd treat a single thing in Python.
- Python Facade Pattern How the Facade Pattern gives you one simple button instead of a confusing control panel in Python.