When updating or adding code, keep control flow and non-trivial expressions easy to reason about.
Rules of thumb:
switch (or equivalent) for branching decisions.let constants (and keep comments aligned with the computation).let bindings and explicit, branch-local variables.Example (turning a hard-to-read expression into named values):
// Before: hard to reason about clamp in a single line
let barLength = min(remainingWidth, max(0, state.finished ? remainingWidth : Int(Int64(remainingWidth) * value / total)))
// After: readable intermediate values
let reservedWidth = (useColor ? joinedComponents.visibleLength : joinedComponents.count) + 45
let completedBarWidth = max(config.width - usedWidth, 1)
let progressWidth = max(0, Int(Int64(completedBarWidth) * value / total))
let currentBarWidth: Int = state.finished ? completedBarWidth : min(completedBarWidth, progressWidth)
let barLength = min(remainingWidth, currentBarWidth)
Example (avoiding nested ternary):
switch progress {
case .plain:
outputMode = .plain
case .color:
outputMode = .color
default:
outputMode = .ansi
}
Apply this during code review to make future changes safer and faster.