Writing Better Go: Lessons from 10 Code Reviews

Summary:

1. Handle Errors

Avoid silently discarding errors (e.g., using the blank identifier _).

Avoid swallowing the error.

When handling errors, you should Check and Handle the Error (e.g., incrementing a failure counter or logging).

Avoid Double Reporting: Log the error, or return it — but not both.

Optimize for the Caller:

return result, nil is Good: The result is valid and safe to use.

return nil, err is Good: The result is invalid; handle the error.

return nil, nil is Bad: This is an ambiguous case that forces extra nil checks.

return result, err is Bad/Unclear: It is unclear which value the caller should trust.

2. Adding Interfaces Too Soon

Interfaces are commonly misused due to Premature Abstraction (often introduced by following object-oriented patterns from languages like Java) or solely to Support Testing. Relying heavily on mocking dependencies for testing can weaken the expressiveness of types and reduce readability.

Don’t Start With Interfaces:

Follow the convention: accept interfaces, return concrete types.

Begin with a concrete type. Only introduce interfaces when you truly need multiple interchangeable types.

Learn more about Writing Better Go: Lessons from 10 Code Reviews

Leave a Reply