blog.stackademic.com 4 min read Original Source

The Go advice I stopped following

I have been writing Go for long enough to have accumulated a list of advice I once treated as gospel.

Clean code rules. Community blog posts. Conference talks. The kind of wisdom that gets retweeted six hundred times and lands in your team’s internal wiki under “how we do things here.”

Some of it aged well. Most didn’t.

Here is the advice I stopped following, and what I do instead.

1. “Always wrap errors with context”

The advice sounded right: wrap every error as it bubbles up the call stack so you always know where it came from.

// The "correct" pattern
func getUser(id string) (*User, error) {
    u, err := db.QueryUser(id)
    if err != nil {
        return nil, fmt.Errorf("getUser: query failed: %w", err)
    }
    return u, nil
}
// The "correct" pattern
func getUser(id string) (*User, error) {
    u, err := db.QueryUser(id)
    if err != nil {
        return nil, fmt.Errorf("getUser: query failed: %w", err)
    }
    return u, nil
}

In a small codebase, sure. In a system where a single request touches six services, you end up with error strings like:

processPayment: validateAccount: fetchBalance: getUser: query failed: context deadline exceeded
processPayment: validateAccount: fetchBalance: getUser: query failed: context deadline exceeded

That is not observability. That is a stack trace dressed up as an error message.

You are duplicating information that structured logging already gives you — function name, file, line number — and paying the allocation cost of fmt.Errorf on every unhappy path.

What I do instead: I usually wrap errors at trust boundaries — when crossing a service call, a database layer, or an external dependency. Inside a single package, let the error propagate as-is and let the logger do the work.

<button data-code="// At the boundary — yes, wrap it
func (s *PaymentService) Process(ctx context.Context, req *ProcessRequest) error {
if err := s.ledger.Debit(ctx, req.AccountID, req.Amount); err != nil {
return fmt.Errorf("debit account %s: %w", req.AccountID, err)
}
return nil
}

// Inside the same package — just return it
func validate(req *ProcessRequest) error {
if req.Amount

// At the boundary — yes, wrap it
func (s *PaymentService) Process(ctx context.Context, req *ProcessRequest) error {
    if err := s.ledger.Debit(ctx, req.AccountID, req.Amount); err != nil {
        return fmt.Errorf("debit account %s: %w", req.AccountID, err)
    }
    return nil
}

// Inside the same package — just return it
func validate(req *ProcessRequest) error {
    if req.Amount <= 0 {
        return ErrInvalidAmount
    }
    return nil
}
// At the boundary — yes, wrap it
func (s *PaymentService) Process(ctx context.Context, req *ProcessRequest) error {
    if err := s.ledger.Debit(ctx, req.AccountID, req.Amount); err != nil {
        return fmt.Errorf("debit account %s: %w", req.AccountID, err)
    }
    return nil
}

// Inside the same package — just return it
func validate(req *ProcessRequest) error {
    if req.Amount <= 0 {
        return ErrInvalidAmount
    }
    return nil
}

2. “Use interfaces everywhere for testability”

The Go community loves interfaces. And interfaces are genuinely powerful. But somewhere along the way, “write testable code” simply became “wrap everything in an interface.“

// You end up with this
type UserRepository interface {
    GetByID(ctx context.Context, id string) (*User, error)
    Create(ctx context.Context, u *User) error
    Update(ctx context.Context, u *User) error
    Delete(ctx context.Context, id string) error
}

// And a mock that's 120 lines and drifts from the real implementation
// the moment someone adds a method
// You end up with this
type UserRepository interface {
    GetByID(ctx context.Context, id string) (*User, error)
    Create(ctx context.Context, u *User) error
    Update(ctx context.Context, u *User) error
    Delete(ctx context.Context, id string) error
}

// And a mock that's 120 lines and drifts from the real implementation
// the moment someone adds a method

The mock becomes a maintenance burden. It does not tell you whether your SQL query is correct.

It does not catch the pgx behavior difference between pgx.ErrNoRows and a real scan error. And it gives you false confidence — your tests are green, but your production queries are wrong.

What I do instead: test database code against a real database. testcontainers-go spins up a real Postgres instance in your CI pipeline.

sqlc-generated code is typed and correct by construction. Interfaces stay where they belong — at service boundaries where you genuinely need to swap implementations.

func TestCreateMember(t *testing.T) {
    ctx := context.Background()
    db := testutil.NewPostgresContainer(t) // real postgres, real schema

    q := db_gen.New(db)
    member, err := q.CreateMember(ctx, db_gen.CreateMemberParams{
        FullName: "Witty",
        Phone:    "+254700000000",
    })

    require.NoError(t, err)
    require.Equal(t, "Witty", member.FullName)
}
func TestCreateMember(t *testing.T) {
    ctx := context.Background()
    db := testutil.NewPostgresContainer(t) // real postgres, real schema

    q := db_gen.New(db)
    member, err := q.CreateMember(ctx, db_gen.CreateMemberParams{
        FullName: "Witty",
        Phone:    "+254700000000",
    })

    require.NoError(t, err)
    require.Equal(t, "Witty", member.FullName)
}

3. “Keep your main package thin”

“Just wire things together in main.” Put your logic in packages, keep main.go to twenty lines. It’s what they said.

This is not wrong exactly, but it leads to a specific failure mode: you end up with a cmd/ folder full of packages that only ever get called from one place, and a main.go that is now twenty lines of “call the bootstrap function in internal/app.”

You added indirection without adding abstraction.

What I do instead: main does real work.

It reads config, initializes the database pool, wires dependencies, starts the gRPC server, and registers the shutdown handler.

If your main.go is two hundred lines but every line is honest wiring — no business logic, no conditionals over feature flags — that is fine.

<button data-code="func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

cfg := config.MustLoad() // panics on bad config — intentional at startup

pool, err := pgxpool.New(ctx, cfg.DatabaseURL)
if err != nil {
log.Fatal("failed to initialize database pool", zap.Error(err))
}
defer pool.Close()

queries := db.New(pool)
memberSvc := members.NewService(queries)

srv := grpc.NewServer(grpc.ChainUnaryInterceptor(
logging.UnaryServerInterceptor(logger),
recovery.UnaryServerInterceptor(),
))

memberspb.RegisterMembersServiceServer(srv, memberSvc)

go func() {
if err := srv.Serve(lis); err != nil {
log.Fatal("server exited", zap.Error(err))
}
}()

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
    defer stop()

    cfg := config.MustLoad() // panics on bad config — intentional at startup

    pool, err := pgxpool.New(ctx, cfg.DatabaseURL)
    if err != nil {
        log.Fatal("failed to initialize database pool", zap.Error(err))
    }
    defer pool.Close()

    queries := db.New(pool)
    memberSvc := members.NewService(queries)

    srv := grpc.NewServer(grpc.ChainUnaryInterceptor(
        logging.UnaryServerInterceptor(logger),
        recovery.UnaryServerInterceptor(),
    ))

    memberspb.RegisterMembersServiceServer(srv, memberSvc)

    go func() {
        if err := srv.Serve(lis); err != nil {
            log.Fatal("server exited", zap.Error(err))
        }
    }()

    <-ctx.Done()
    srv.GracefulStop()
}
func main() {
    ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
    defer stop()

    cfg := config.MustLoad() // panics on bad config — intentional at startup

    pool, err := pgxpool.New(ctx, cfg.DatabaseURL)
    if err != nil {
        log.Fatal("failed to initialize database pool", zap.Error(err))
    }
    defer pool.Close()

    queries := db.New(pool)
    memberSvc := members.NewService(queries)

    srv := grpc.NewServer(grpc.ChainUnaryInterceptor(
        logging.UnaryServerInterceptor(logger),
        recovery.UnaryServerInterceptor(),
    ))

    memberspb.RegisterMembersServiceServer(srv, memberSvc)

    go func() {
        if err := srv.Serve(lis); err != nil {
            log.Fatal("server exited", zap.Error(err))
        }
    }()

    <-ctx.Done()
    srv.GracefulStop()
}

That is readable. It is also the real application topology, visible in one file.

4. “Never panic in library code”

This one is correct for libraries. But actively harmful when applied to application code wholesale.

If your application starts and the database URL is empty, you do not want to return an error from main.

You want to crash immediately with a message that makes the misconfiguration obvious. log.Fatal and even panic at initialization time are features, not sins.

The same applies to programmer errors: a nil pointer passed where one is structurally impossible is a bug, not a recoverable error. Returning error for it lets the bug propagate silently.

// This is fine in application startup
func mustConnectDB(cfg Config) *pgxpool.Pool {
    pool, err := pgxpool.New(context.Background(), cfg.DatabaseURL)
    if err != nil {
        panic(fmt.Sprintf("failed to initialize database pool: %v", err))
    }
    return pool
}
// This is fine in application startup
func mustConnectDB(cfg Config) *pgxpool.Pool {
    pool, err := pgxpool.New(context.Background(), cfg.DatabaseURL)
    if err != nil {
        panic(fmt.Sprintf("failed to initialize database pool: %v", err))
    }
    return pool
}

Reserve graceful error handling for runtime conditions: network timeouts, transient failures, user input. Fail loudly for configuration mistakes and programmer errors.

5. “Always pass context”

Context propagation is correct and important.

But the advice becomes a cargo cult when developers add ctx to every function signature — including pure functions with no I/O — because a linter or a PR comment said so.

// This does not need a context
func calculateInstallments(principal float64, rate float64, months int) []Installment {
    // pure math, no I/O, no goroutines
}
// This does not need a context
func calculateInstallments(principal float64, rate float64, months int) []Installment {
    // pure math, no I/O, no goroutines
}

Context has a cost: it is an argument that must be threaded everywhere, it makes signatures noisier, and it tempts developers to use context.WithValue for dependency injection (seriously, do not do this).

Pass context where it will actually be used — database calls, HTTP clients, gRPC stubs, anything that blocks on I/O or needs cancellation.

Do not pass it to pure functions, domain logic, or anything that will return in microseconds regardless of cancellation.

In summary, every piece of advice above was correct in the context it was written for.

Error wrapping makes sense when you are writing a library. Interfaces make sense at service boundaries. Thin main makes sense when your startup logic is genuinely complex enough to warrant separation.

The mistake is applying advice as a rule rather than understanding it as a heuristic.

Go’s design philosophy is already doing a lot of the work for you — the type system, the explicitness, the absence of magic.

Trust the language. Add structure where the structure earns its cost. Remove it where it does not.

Thanks for reading. Read these too

We removed three popular Go Libraries — And the code got better
Fewer Abstractions, Better Systems: What really Happened When We Removed 3 Go Libraries

Forget perfect microservices — build this instead
Complexity feels smart — until it starts slowing everything down

I Stopped Writing Tests This Way — Everything Improved
Get this right once and you’ll never write tests badly in any of your Go projects again.