Software design and clean code

Stage 1 of 10 · 8 lessons · ~3 weeks

Object-oriented programming properly

Go beyond the textbook definitions: use classes to protect rules, interfaces to hide change, polymorphism to remove type checks and composition instead of deep inheritance, in your language's modern style.

Start: Classes, objects and responsibilities

Lessons· one lesson for each topic, in this order

  1. 1Classes, objects and responsibilities
  2. 2Encapsulation and invariants
  3. 3Abstraction and interfaces
  4. 4Inheritance, used sparingly
  5. 5Polymorphism instead of type checks
  6. 6Composition over inheritance
  7. 7Value objects and immutabilityOptional
  8. 8Pythonic OOP: dataclasses, Protocol and properties

Do this

  • Rewrite one old project class so that all fields are private and every rule is enforced in a method.
  • Replace one if or switch on a type field with an interface and two classes.
  • Refactor one inheritance you wrote for code reuse into composition.
  • Write a small immutable value type, such as Money or Email, with its own validation.
  • Write unit tests that prove your invariants cannot be broken from outside.

Start with· follow one of these

Practise

  • Free exercises in your language with optional human mentoring on design, not just on passing tests

Keep handy

  • Read chapter 9, Classes, then the dataclasses and typing pages in the standard library docs

Also worth your time

Before moving on: A small domain model you wrote from a one-paragraph brief, such as a library or a clinic, with private state, at least one interface with two implementations, no type switches and composition wherever inheritance was tempting, plus unit tests for its rules.

Tauseef's advice
Python lets you skip classes entirely, and often you should: a function or a dataclass is frequently the better design. Use classes when there is state with rules to protect, and use Protocol for interfaces so a type checker can check your design.

Mark this stage as not done?