Go

Lesson 02

Naming and exported APIs

Export only the names callers need and avoid repeating the package name inside exported identifiers.

Good Code

reviews/repository.go
package reviews

type Repository interface {
    Find(ctx context.Context, id string) (Review, error)
    Save(ctx context.Context, review Review) error
}

type Review struct {
    ID     string
    Title  string
    Status Status
}

type Status string

Bad Code

reviews/repository.go
package reviews

type ReviewsRepositoryInterface interface {
    GetReviewObjectFromReviewID(ctx context.Context, reviewID string) (ReviewObject, error)
    SaveReviewObjectToDatabase(ctx context.Context, reviewObject ReviewObject) error
}

type ReviewObject struct {
    ReviewID     string
    ReviewTitle  string
    ReviewStatus string
}

Review Notes

What to review

Good Code

The good version uses the package name to provide context, so callers read reviews.Repository, reviews.Review, and reviews.Status.

Bad Code

The bad version repeats "review" and implementation detail in every exported name. The API gets noisy and harder to change.

Takeaways

  • Exported names are part of the package contract, so they should be minimal, clear, and caller-oriented.