Python course / Applied
Patterns and architecture
Give a growing program a shape: a pure core, a thin shell, and pieces you can swap. Most architecture problems start as one class quietly doing three jobs.
- strategies
- registries
- composition
- pure core
- repositories
- state machines
- undo
- configuration
Runs in your browser. Start straight away; create an account when you want your progress kept.
COMMANDS = {}
def command(name):
def register(func):
COMMANDS[name] = func
return func
return register
@command("add")
def add(basket, item):
return basket + [item]
@command("clear")
def clear(basket, item):
return []
basket = []
for name, item in [("add", "tea"), ("add", "jam"), ("clear", None)]:
basket = COMMANDS[name](basket, item)
print(name, "->", basket)
add -> ['tea'] add -> ['tea', 'jam'] clear -> []
What you will learn
- Replace a chain of if and elif choosing a behaviour with a dictionary of functions, so adding one is a single line.
- Register command handlers with a decorator into a dictionary, and dispatch text commands through it.
- Replace a family of subclasses, one per combination of choices, with one class built from the pieces it is given.
- Split a program into pure functions that decide and a thin outer layer that reads and prints, so the decisions can be tested with no input or output at all.
- Put storage behind a small set of methods, with an in-memory version and a file version that pass the same tests.
- Model something with a fixed set of states and allowed moves as a transition table, refusing moves the table does not allow.
The lessons in this module
- A class that should be a function
- Strategies as functions
- A registry of commands
- Composition over inheritance
- Events: telling whoever is listening
- A pure core and a thin shell
- Repositories: storage behind a promise
- Wiring it together in one place
- State machines
- Commands that can be undone
- Settings checked at the door
- Errors that belong to your code
- Refactoring under a safety net
- When the pattern is the problem
- Capstone: the café
- Module review: a basket with undo
Ready when you are
Previous: Testing. All modules are on the course page.