Design packages and dependency contracts
Design packages and dependency contracts
Separate the word-count rule from transport and storage. A core package owns Job, Result and service errors; an HTTP adapter translates requests and responses; a repository adapter implements an interface defined by the consumer. The command package assembles dependencies. Keep the interface small: Put(ctx, job, result) returns the existing or inserted result, a created flag, and an error. Specify atomic compare-and-insert as part of the interface, because a method signature alone cannot enforce that behavior.
package main
import ( "fmt" "strings")
type Counter interface{ Count(string) int }type words struct{}
func (words) Count(s string) int { return len(strings.Fields(s)) }func process(c Counter, s string) int { return c.Count(s) }func main() { fmt.Println(process(words{}, "Go makes tools"))}This example demonstrates dependency direction, not a requirement to wrap every pure function in an interface. strings.Fields can be called directly; an interface is useful when alternate implementations, test doubles or external dependencies justify it. The transport should not know SQL syntax, and the core should not import net/http. In the companion module, core, memstore, httpapi and cmd/jobd form a directed dependency graph.
Expected output:
3Make failure semantics explicit
package main
import ( "context" "errors" "fmt")
var ErrConflict = errors.New("conflict")
func save() error { return fmt.Errorf("save job: %w", ErrConflict) }func main() { fmt.Println(errors.Is(save(), ErrConflict)) fmt.Println(errors.Is(save(), context.Canceled))}Wrapping with %w preserves classification via errors.Is while adding context. Do not expose internal storage error messages directly to HTTP clients. Map known domain errors to documented statuses and unknown errors to a generic 500. Avoid dependency cycles by keeping interfaces and domain errors in the core. Tests should verify behavior against the interface contract, including concurrent insertions, not only the mock call count.
Expected output:
truefalseTry it locally
Define a Store interface with Put(context.Context,string) error. Inject a test store returning a sentinel unavailable error; wrap it and verify errors.Is still succeeds.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Capstone engineering 02: Design packages and dependency contracts
Check the lesson objective before moving on.
Where should the repository interface used by the core live?
Why wrap an error with %w?