Go

Lesson 06

Struct validation and zero values

Design structs so zero values are either useful or validated before the value crosses an important boundary.

Good Code

reviews/review.go
type Review struct {
    ID    string
    Title string
    Body  string
}

func NewReview(id string, title string, body string) (Review, error) {
    title = strings.TrimSpace(title)
    if id == "" {
        return Review{}, errors.New("id is required")
    }
    if title == "" {
        return Review{}, errors.New("title is required")
    }

    return Review{ID: id, Title: title, Body: body}, nil
}

Bad Code

reviews/review.go
type Review struct {
    ID    string
    Title string
    Body  string
}

func CreateReview(id string, title string, body string) Review {
    return Review{
        ID:    id,
        Title: title,
        Body:  body,
    }
}

Review Notes

What to review

Good Code

The good version makes invalid construction visible and returns a useful error before the value enters the rest of the system.

Bad Code

The bad version allows empty IDs and titles to move through the codebase as if they were valid reviews.

Takeaways

  • A zero value can be a feature, but domain objects still need clear validity rules.