Skip to content

Latest commit

 

History

History
112 lines (87 loc) · 7.28 KB

File metadata and controls

112 lines (87 loc) · 7.28 KB

Writing idiomatic, effective, and clean Go code

Writing idiomatic, effective, and clean Go code involves adhering to a set of principles and practices that leverage the language's unique design. Here are some key guidelines, often considered "commandments" in the Go community:

The Ten Commandments of Idiomatic Go:

  1. Thou Shalt Format Thy Code with golangci-lint:

    • Guideline: Use the golangci-lint tool religiously. It enforces a standard, opinionated style for indentation, spacing, and alignment. We support the tool directly in our Makefile. You can run:
    make lint

    and

    make checks
  2. Thou Shalt Handle Errors Explicitly:

    • Guideline: Go treats errors as values. Functions that can fail should return an error as the last return value. Always check error returns and handle them gracefully. Avoid ignoring errors using the blank identifier _. Propagate errors back up the call stack or handle them appropriately (e.g., logging, retrying). Use errors.Is and errors.As for checking error types or values, especially in Go 1.13+. Error strings should be lowercase and not end with punctuation.
    • References:
  3. Thou Shalt Favor Composition Over Inheritance:

    • Guideline: Go does not have traditional class inheritance. Achieve code reuse and flexibility through composition (embedding structs) and interfaces. Design small, focused interfaces that define behavior.
    • References:
  4. Thou Shalt Design Small, Focused Interfaces:

    • Guideline: Go's interfaces are implicitly implemented. Define interfaces on the consumer side, specifying only the methods a client needs. This promotes decoupling and testability. Name interfaces with an "-er" suffix (e.g., Reader, Writer) when they define a single method, though this is a convention, not a strict rule for all interfaces.
    • References:
  5. Thou Shalt Write Concurrent Code Using Goroutines and Channels:

  6. Thou Shalt Not Use Global Variables Extensively:

  7. Thou Shalt Keep Functions Small and Single-Purpose:

  8. Thou Shalt Write Tests:

  9. Thou Shalt Document Exported Symbols:

  10. Thou Shalt Be Mindful of Performance and Allocations:

    • Guideline: While Go is performant, be aware of potential bottlenecks. Understand how slices, maps, and pointers work to minimize unnecessary allocations and garbage collection pressure, especially in performance-critical code. Use tools like the pprof profiler to identify performance issues.

Additional Recommended Reading and Style Guides:

These resources provide more detailed explanations and examples for each of the guidelines mentioned above, helping you to write more effective and idiomatic Go code.