Menu

1 / 2

Stop Indenting — 6 Patterns for Flattening Nested if/else in Go

DEV Community·Bala Paranj·6 months ago
#KnIQRqaY
#pattern#before#after#go#return
Reading 0:00
15s threshold

Every level of indentation is a level of mental context the reader must hold. Three levels deep and you're debugging the structure, not the logic. Four levels and you've lost the plot entirely.

I found 6 patterns of unnecessary nesting across a Go CLI and flattened each one. Here's the before/after for each.

Pattern 1: Inverted Loop Condition — Early Continue

Before: Entire loop body nested inside a conditional

for _ , sf := range suffixes { if strings . HasSuffix ( upper , sf . label ) { numStr := strings . TrimSpace ( s [ : len ( s ) - len ( sf . label )]) n , err := strconv . ParseInt ( numStr , 10 , 64 ) if err != nil { return 0 , fmt . Errorf ( "invalid byte size %q: %w" , s , err ) } if n <= 0 { return 0 , fmt . Errorf ( "byte size must be positive: %q" , s ) } return n * sf . multiplier , nil } }

Enter fullscreen mode

Exit fullscreen mode

The entire loop body — parsing, validation, return — is nested one level deep because of the HasSuffix check.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.