Design cohesive packages and explicit dependencies
Design cohesive packages and explicit dependencies
A cohesive package groups behavior that changes for the same reason. Explicit dependencies are collaborators passed through a constructor or function, rather than hidden global state. For a notification service, the consumer needs the ability to send a message, not every operation of a mail provider. Define a narrow interface at the consumer when substitution is useful.
package main
import ( "fmt")
type Sender interface{ Send(string) error }type Notice struct{ sender Sender }
func NewNotice(s Sender) Notice { return Notice{sender: s} }func (n Notice) Welcome(name string) error { return n.sender.Send("Welcome " + name) }
type Recorder struct{ Messages []string }
func (r *Recorder) Send(s string) error { r.Messages = append(r.Messages, s); return nil }func main() { r := &Recorder{} n := NewNotice(r) if err := n.Welcome("Ada"); err != nil { panic(err) } fmt.Println(r.Messages[0])}Notice owns message construction; Recorder owns recording. In a multi-package application the notice package can declare Sender without importing the recorder package. A composition root (typically main) constructs both. The constructor here assumes a valid nonnil Sender. Keep that precondition explicit; an interface containing a typed nil is not itself nil.
Expected output:
Welcome AdaMake dependency failure observable
package main
import ( "errors" "fmt")
type SendFunc func(string) error
func notify(send SendFunc) error { return send("ready") }func main() { err := notify(func(string) error { return errors.New("offline") }) fmt.Println(err)}A single operation may need only a function parameter. Returning the error lets the caller choose recovery. Avoid creating a package for every small function or an interface for every struct: group business responsibilities, keep dependencies acyclic, and use concrete types when no boundary needs substitution. The companion module demonstrates actual imports.
Expected output:
offlineTry it locally
Create a report function accepting io.Writer. Write the line ready and return the write error; call it with a bytes.Buffer and print the captured line.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Professional architecture 01: Design cohesive packages and explicit dependencies
Check the lesson objective before moving on.
Where should a narrow Sender interface normally live?
Why pass the writer explicitly?