Maintainable Python Design and Testing
Separate responsibilities and test the boundary between collaborating parts.
python, pep8, testing, integration, design patterns, solid, clean codeSeparate a decision from its storage
Maintainable code makes responsibilities, contracts, and failure paths understandable. A small service can depend on an interface rather than choosing a particular database. This supports testing and change without claiming that an interface alone makes the system correct.
Python illustration
from typing import Protocol
class Notes(Protocol):
def add(self, title: str) -> None: ...
class MemoryNotes:
def __init__(self):
self.items: list[str] = []
def add(self, title: str) -> None:
self.items.append(title)
def save_title(notes: Notes, title: str) -> None:
if not title.strip():
raise ValueError("title is required")
notes.add(title)
store = MemoryNotes()
save_title(store, "Read")
print(store.items)
Prepared output — not live execution:
['Read']
The service checks the rule, then uses the add operation. The in-memory
implementation supplies that operation without being named in the function.
The example preserves the supplied title; it only checks for blank text.
See the reasoning
Trace responsibility across a boundary
See what the service checks and what the storage object does. This is a prepared demonstration, not live code execution.
Supply a title
- Callersave_title(store, Read)Current focus
- Servicevalidation pending
- Storageitems: []
The caller passes an object with add and a title.
Test and refine
A unit test could use a small fake to check that a blank title raises
ValueError without calling add. An integration test could use a real
repository and a disposable test database to verify a write and read
together; clean up safely and never point tests at production data.
Test failure paths as well as success.
For the definitions above, a focused local unit test can use unittest.mock:
from unittest import TestCase
from unittest.mock import Mock
class SaveTitleTests(TestCase):
def test_blank_title_never_reaches_storage(self):
store = Mock()
with self.assertRaises(ValueError):
save_title(store, " ")
store.add.assert_not_called()
Place the example definitions and this test in an importable local test
module, then run python -m unittest. This checks one failure boundary;
it does not replace an integration test against the actual repository.
For a small integration example, reuse save_title with a SQLite-backed
implementation in a disposable in-memory database:
import sqlite3
from contextlib import closing
class SqliteNotes:
def __init__(self, connection):
self.connection = connection
def add(self, title):
self.connection.execute("INSERT INTO notes VALUES (?)", (title,))
with closing(sqlite3.connect(":memory:")) as connection:
with connection:
connection.execute("CREATE TABLE notes (title TEXT NOT NULL)")
save_title(SqliteNotes(connection), "Read")
row = connection.execute("SELECT title FROM notes").fetchone()
assert row == ("Read",)
This example has no printed output. It checks the service and repository together against SQLite, not a deployed database or every error condition.
PEP 8 recommends consistent naming, indentation, and formatting. Clear names, small focused functions, explicit errors, and avoiding needless duplication are useful clean-code practices, but rules should not obscure the code. A Strategy pattern can substitute one behaviour behind an interface; a Factory can centralise object creation. Use patterns when they solve an actual problem, not as mandatory layers.
SOLID is a set of design heuristics: single responsibility groups a coherent reason for change; open/closed favours extension without unnecessary modification; Liskov substitution requires subtypes to honour their contracts; interface segregation favours focused interfaces; and dependency inversion makes high-level policy depend on abstractions. These principles involve trade-offs and do not replace tests or judgement.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
