Early Returns
Go encourages a “flat” coding style by using early returns and guard clauses. This pattern avoids deeply nested if/else blocks.
The Problem: Deep Nesting
Nested logic is hard to follow because the reader has to keep multiple “what if” scenarios in their head.
func getInsuranceAmount(status status) int {
if !status.hasInsurance() {
return 1
} else {
if status.isTotaled() {
return 10000
} else {
// ... and so on
}
}
}
The Solution: Guard Clauses
A guard clause checks for an “error” or “exit” condition and returns immediately, allowing the main logic to continue in a single column.
func getInsuranceAmount(status status) int {
if !status.hasInsurance() {
return 1
}
if status.isTotaled() {
return 10000
}
if status.isBigDent() {
return 270
}
return 160
}
Benefits
- Reduced Cognitive Load: You only need to think about one condition at a time.
- Readability: The “happy path” of the function is usually at the bottom, while edge cases are handled and disposed of early.