Created
March 14, 2026 15:13
-
-
Save mohashari/9b989a481ee20c50d5c23199c086b969 to your computer and use it in GitHub Desktop.
Code snippets — Clean Code Principles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Bad: This function does 3 things | |
| func processUser(userID string) error { | |
| // 1. Validate | |
| if userID == "" { | |
| return errors.New("user ID required") | |
| } | |
| // 2. Fetch from DB | |
| user, err := db.GetUser(userID) | |
| if err != nil { | |
| return err | |
| } | |
| // 3. Send welcome email | |
| return emailService.SendWelcome(user.Email, user.Name) | |
| } | |
| // Good: Each function does one thing | |
| func validateUserID(userID string) error { | |
| if userID == "" { | |
| return errors.New("user ID required") | |
| } | |
| return nil | |
| } | |
| func sendWelcomeEmail(ctx context.Context, userID string) error { | |
| user, err := userRepo.Get(ctx, userID) | |
| if err != nil { | |
| return fmt.Errorf("fetch user: %w", err) | |
| } | |
| return emailService.SendWelcome(ctx, user.Email, user.Name) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Hard to read | |
| func generateReport(orders []Order) Report { | |
| var total float64 | |
| var byCategory = make(map[string]float64) | |
| for _, o := range orders { | |
| total += o.Amount | |
| byCategory[o.Category] += o.Amount | |
| } | |
| topCategory := "" | |
| topAmount := 0.0 | |
| for cat, amt := range byCategory { | |
| if amt > topAmount { | |
| topAmount = amt | |
| topCategory = cat | |
| } | |
| } | |
| return Report{Total: total, TopCategory: topCategory} | |
| } | |
| // Easy to read | |
| func generateReport(orders []Order) Report { | |
| total := sumOrderAmounts(orders) | |
| byCategory := groupByCategory(orders) | |
| topCategory := findTopCategory(byCategory) | |
| return Report{Total: total, TopCategory: topCategory} | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Bad | |
| if retries > 3 { | |
| sleep(500) | |
| } | |
| // Good | |
| const ( | |
| maxRetries = 3 | |
| retryDelayMs = 500 | |
| ) | |
| if retries > maxRetries { | |
| sleep(retryDelayMs * time.Millisecond) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Bad: swallowing errors | |
| func getUser(id string) *User { | |
| user, _ := db.Find(id) // Silently ignores error | |
| return user | |
| } | |
| // Bad: handling errors at wrong level | |
| func saveOrder(order Order) { | |
| if err := db.Save(order); err != nil { | |
| log.Printf("error: %v", err) // Log and continue?! | |
| } | |
| } | |
| // Good: return errors, let callers decide | |
| func getUser(ctx context.Context, id string) (*User, error) { | |
| user, err := db.Find(ctx, id) | |
| if err != nil { | |
| return nil, fmt.Errorf("get user %s: %w", id, err) | |
| } | |
| return user, nil | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Bad: what does "true" mean here? | |
| createUser("alice@example.com", true, false) | |
| // Good: named parameters (or options pattern) | |
| createUser(CreateUserOptions{ | |
| Email: "alice@example.com", | |
| SendWelcomeEmail: true, | |
| RequireVerification: false, | |
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Bad: pyramid of doom | |
| func processOrder(order Order) error { | |
| if order.UserID != "" { | |
| if order.Items != nil { | |
| if len(order.Items) > 0 { | |
| if order.Total > 0 { | |
| // Actual logic buried here | |
| return db.Save(order) | |
| } else { | |
| return errors.New("total must be positive") | |
| } | |
| } else { | |
| return errors.New("order must have items") | |
| } | |
| } else { | |
| return errors.New("items required") | |
| } | |
| } else { | |
| return errors.New("user ID required") | |
| } | |
| } | |
| // Good: guard clauses + early returns | |
| func processOrder(order Order) error { | |
| if order.UserID == "" { | |
| return errors.New("user ID required") | |
| } | |
| if len(order.Items) == 0 { | |
| return errors.New("order must have items") | |
| } | |
| if order.Total <= 0 { | |
| return errors.New("total must be positive") | |
| } | |
| return db.Save(order) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Bad: comment restates the code | |
| // Increment counter by 1 | |
| counter++ | |
| // Bad: commented-out code | |
| // user.SendEmail() | |
| // user.NotifySlack() | |
| // Good: explains a non-obvious decision | |
| // Use exponential backoff starting at 100ms to avoid thundering herd | |
| // when the upstream service recovers from an outage | |
| delay := 100 * math.Pow(2, float64(attempt)) * time.Millisecond |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Bad | |
| func TestGetUser(t *testing.T) { ... } | |
| // Good | |
| func TestGetUser_ReturnsUser_WhenExists(t *testing.T) { ... } | |
| func TestGetUser_ReturnsNotFoundError_WhenMissing(t *testing.T) { ... } | |
| func TestGetUser_ReturnsError_WhenDatabaseFails(t *testing.T) { ... } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Bad | |
| func calc(d []int, t int) int { | |
| r := 0 | |
| for _, v := range d { | |
| if v > t { | |
| r++ | |
| } | |
| } | |
| return r | |
| } | |
| // Good | |
| func countValuesAboveThreshold(values []int, threshold int) int { | |
| count := 0 | |
| for _, value := range values { | |
| if value > threshold { | |
| count++ | |
| } | |
| } | |
| return count | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment