The previous note showed that packaging code into a function makes it reusable. This note asks a sharper question: reusable by whom, and safely how? A function that nobody but its own author understands is barely more useful than no function at all — every call site would need to re-read the implementation to know what it does. A specification is a short, precise contract stating what a function needs from its caller and what it promises in return, written before worrying about how the body achieves it. This is also the foundation of top-down design: stubbing out a program as a hierarchy of specified-but-unimplemented functions before filling in any bodies, so the overall structure is settled while the details are still open.
Learning objectives. By the end of this note you should be able to:
- write a docstring-based specification stating a function's assumptions (preconditions on its parameters) and guarantees (what it promises to return);
- explain the abstraction/decomposition distinction and why both matter for working in a team or on a program too large to hold in your head at once;
- generalise a previously-hard-coded function (e.g.
bisection_sqrt) into a more broadly useful one guided by its specification; - practice top-down design by stubbing a small multi-function program's signatures and specifications before implementing any bodies.
In this lesson
- Specifications: assumptions and guarantees
- Abstraction and decomposition
- Top-down design
Before you start
The full lesson, with worked examples and exercise solutions, is for members.
Read the full lessonNew to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.