Good Code
The good version makes invalid construction visible and returns a useful error before the value enters the rest of the system.
Lesson 06
Design structs so zero values are either useful or validated before the value crosses an important boundary.
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
}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,
}
}The good version makes invalid construction visible and returns a useful error before the value enters the rest of the system.
The bad version allows empty IDs and titles to move through the codebase as if they were valid reviews.