Clean Code
Readable code makes contracts, responsibilities, and failure paths easy to locate. Short functions are helpful when they express a coherent idea, not when they merely move complexity elsewhere.
What you’ll understand
- Readable code makes contracts, responsibilities, and failure paths easy to locate. Short functions are helpful when they express a coherent idea, not when they merely move complexity elsewhere.
- Practice explaining a design decision with an example and a boundary case.
Name the domain decision
Compare handle(data) with reserveCompatibleSpace(vehicle). The second name reveals intent and gives the reader a place to look for compatibility rules. Keep names honest: a method named canReserve should not secretly reserve a space. Distinguish queries from commands when it makes side effects clearer.
- Name units in values such as weightGrams or amountCents.
- Return a meaningful result for expected rejection.
- Avoid a boolean parameter whose meaning changes by caller.
Make state changes easy to review
Validate before mutating, group related state transitions, and avoid exposing collections that callers can change behind the owner’s back. Extract repeated business knowledge rather than every repeated expression. Use small tests to make intended behavior visible.
- Keep boundary conversion at the boundary.
- Prefer explicit branches over hidden sentinel conventions.
- Describe errors without erasing their cause.
Refactor with a contract in view
A refactor should preserve observable behavior unless a requirement intentionally changes. First capture representative outcomes, then move responsibilities. If every refactor requires rewriting unrelated tests, inspect whether the tests depend on implementation details rather than contracts.
- Can a reader find the invariant without tracing five files?
- Does one helper have several unrelated reasons to change?
- Is the abstraction simpler than the code it replaced?