Chapter 07
Principles beyond SOLID
Short rules that sit next to SOLID in code reviews, and the anti-patterns that appear when they are ignored.
Dependency injection
Also called DI, constructor injection, inversion of control
- What
- An object receives its collaborators from outside, usually through its constructor, instead of creating them itself.
- Why
- It is the practical way to apply dependency inversion and to swap real services for fakes in tests.
Watch out
Pulling in a heavy DI framework for a small app where passing arguments by hand is clearer.
DRY
Also called Do not repeat yourself
- What
- Every piece of knowledge should have one authoritative place in the code.
- Why
- Duplicated rules drift apart, and a bug fixed in one copy survives in the other.
Watch out
Merging code that only looks alike but changes for different reasons, which couples unrelated features.
KISS and YAGNI
Also called keep it simple, you aren't gonna need it
- What
- Prefer the simplest design that works (KISS), and do not build for requirements you do not have yet (YAGNI).
- Why
- Speculative flexibility costs time now and usually guesses the future wrong.
Law of Demeter
Also called principle of least knowledge, train wreck
- What
- A method should talk only to its own fields, its parameters and objects it creates, not reach through chains like
order.customer.address.city. - Why
- Long chains couple code to the internal structure of many classes at once.
High cohesion, low coupling
Also called cohesion, coupling
- What
- Cohesion: things inside a module belong together. Coupling: how much modules depend on each other's details. Aim for high cohesion and low coupling.
- Why
- This pair is what most patterns and principles are trying to improve.
Common anti-patterns
Also called god object, spaghetti code, code smell
- What
- Recurring bad shapes: the god object that knows everything, spaghetti code with tangled control flow, copy-paste programming, and magic numbers.
- Why
- Naming the smell makes it easier to argue for a refactor in a review.
- Example
- A 3,000-line
Utilsclass used by every module is a god object; split it by responsibility.