Python design, part 1 of 2
Python Design Principles
Design principles are habits that keep code easy to change. They come in two groups: the five SOLID principles for designing classes, and six general rules of thumb. Each chapter shows one principle on the same small bank: first the code that breaks it, then the fix. Examples run on Python 3.9 or newer with only the standard library.
The bank we will use
Every example builds on two classes: a Person and an Account. Save this as bank.py. Later chapters import from it and change only what the principle is about.
How to read the chapters: before.py is the code that works today but will hurt later. after.py is the same feature with the principle applied.
SOLID principles
Group 1 of 2 · five rules for designing classes
SOLID is an acronym for five principles about how classes should be shaped and how they should depend on each other. They were collected by Robert C. Martin, and each letter stands for one principle.
- S: Single responsibility, one class does one job
- O: Open/closed, add new behaviour without editing old code
- L: Liskov substitution, a child class can stand in for its parent
- I: Interface segregation, many small interfaces beat one large one
- D: Dependency inversion, depend on abstractions, not on details
Single responsibility
A class should have one reason to change. If the bank changes its rules, its statement layout and its storage, three different people will want to edit this one class.
Split it by reason to change. Account keeps the money rules, one class formats, one class stores.
Test: describe the class in one sentence. If you need the word "and", it is doing more than one job.
Open/closed
Code should be open for extension and closed for modification. Adding a new kind of account should mean adding code, not editing code that already works.
Let each account type carry its own rate. The function never changes again.
Signal: a growing if/elif chain on a "type" value is usually asking to become separate classes or a dictionary of functions.
Liskov substitution
Anywhere a parent class works, a child class must work too. A fixed deposit that inherits withdraw() and then refuses to do it breaks every function written for Account.
Do not inherit a promise you cannot keep. Put withdraw() only on the classes that support it.
Signal: a subclass method that raises NotImplementedError, or does nothing, means the inheritance is wrong.
Interface segregation
Do not force a class to implement methods it does not need. One large interface for every bank product makes a home loan pretend it can accept deposits.
Use several small interfaces. In Python a Protocol describes "anything with this method" without inheritance.
Dependency inversion
High-level rules should not depend on low-level details. Both should depend on an abstraction. Here the transfer rule is welded to SMS, so it cannot send email and cannot be tested without sending a message.
Describe what the service needs, and pass the real thing in from outside. This is also called dependency injection.
Payoff: in a test, pass a fake notifier that stores messages in a list. No SMS, no network, and the transfer rule is still fully tested.
General principles
Group 2 of 2 · rules of thumb for any code
These are shorter and older than SOLID, and they apply to functions and scripts as much as to classes. The first three are about how much code to write. The last three are about where data and decisions should live.
- DRY: write each rule once
- KISS: prefer the simplest thing that works
- YAGNI: do not build for needs you do not have yet
- Composition over inheritance: build objects from parts
- Tell, don't ask: let an object make its own decisions
- Encapsulation: keep data private, expose behaviour
DRY: don't repeat yourself
Every rule should live in one place. Here the rule "an amount is a positive number" is written twice, so one day it will be fixed in one method and forgotten in the other.
Careful: DRY is about repeated knowledge, not repeated characters. Two lines that look alike but change for different reasons should stay separate.
KISS: keep it simple
The simplest code that solves the problem is the easiest to read, test and fix. This check needs one comparison, not two classes and a lambda.
Rule of thumb: start with a function. Reach for a class when there is state to keep, and for a pattern when the simple version has actually become painful.
YAGNI: you aren't gonna need it
Build what is needed today. Features added "for later" must be tested and maintained now, and the guess about later is usually wrong.
The class from chapter 1 already does everything the bank needs. When foreign currency really arrives, adding it is one small change made with real requirements in hand.
Composition over inheritance
Inheritance says "is a". Composition says "has a". When features can be mixed freely, inheritance needs one class per combination.
Make the feature its own small object and hand it to the account.
When to inherit: only when the child truly is a kind of the parent and keeps all of its promises (see Liskov substitution).
Tell, don't ask
Do not ask an object for its data and then make its decision for it. Tell it what you want and let it apply its own rules.
The Law of Demeter
A close relative: talk to your direct neighbour, not to its internals. Long dotted chains break when anything in the middle changes.
Encapsulation
Keep data private and expose behaviour. If anyone can assign to balance, none of the rules in deposit() and withdraw() can be trusted.
A leading underscore marks the attribute as internal. A property without a setter makes it readable but not assignable.
Quick reference
One question to ask for each principle while reviewing code.
| Principle | Ask yourself |
|---|---|
| Single responsibility | Can I describe this class without saying "and"? |
| Open/closed | Can I add a new case without editing old code? |
| Liskov substitution | Does every subclass keep every promise of its parent? |
| Interface segregation | Is any class forced to implement a method it does not use? |
| Dependency inversion | Can I swap this dependency for a fake in a test? |
| DRY | Is this rule written in exactly one place? |
| KISS | Is there a simpler version that does the same job? |
| YAGNI | Does anyone need this today? |
| Composition over inheritance | Is this "is a", or really "has a"? |
| Tell, don't ask | Am I making a decision that belongs to another object? |
| Encapsulation | Can outside code break this object's rules? |
The first five are known together as SOLID. Principles tell you what good code looks like. Design patterns are named, reusable ways to get there. Continue with Python Design Patterns, which uses the same bank.