xb

Builder Best Practices (English)

English rewrite of xb/doc/BUILDER_BEST_PRACTICES.md. It captures conventions field teams use to keep builders predictable and readable.


1. Modeling inputs


2. Chaining style

Tip Why it helps
Group related conditions Easier to scan, reuse via helper functions
Use Cond(func(cb *CondBuilder)) Better than stacking Or() calls with manual parentheses
Keep method ordering consistent Select → From → Join → Where → Sort → Limit mirrors SQL
Avoid side effects inside closures Builders are pure data; keep IO outside

3. Reusable blocks

func addTenantGuard(b *xb.Builder, tenantID uint64) *xb.Builder {
    return b.Eq("tenant_id", tenantID)
}

func addPagination(b *xb.Builder, req *PageRequest) *xb.Builder {
    return b.Limit(req.Limit()).Offset(req.Offset())
}

4. Observability


5. Safety rails


6. Further reading