Compare layered, hexagonal and modular designs
Compare layered, hexagonal and modular designs
Layered architecture groups responsibilities such as transport, application and persistence. Hexagonal architecture (ports and adapters) places application behavior behind ports that external adapters implement or call. A modular monolith groups cohesive business capabilities inside one deployable application. These approaches can coexist.
package main
import ( "errors" "fmt")
type Catalog interface{ Price(string) (int, bool) }type Checkout struct{ catalog Catalog }
func (c Checkout) Total(id string, count int) (int, error) { if count < 1 || count > 10 { return 0, errors.New("quantity") } p, ok := c.catalog.Price(id) if !ok { return 0, errors.New("unknown item") } if p < 0 || p > 100000 { return 0, errors.New("price") } return p * count, nil}
type MemoryCatalog map[string]int
func (m MemoryCatalog) Price(id string) (int, bool) { v, ok := m[id]; return v, ok }func main() { c := Checkout{catalog: MemoryCatalog{"tea": 300}} n, e := c.Total("tea", 2) fmt.Println(n, e) _, e = c.Total("coffee", 1) fmt.Println(e)}Checkout declares the price lookup port; MemoryCatalog implements it. This toy port only distinguishes presence, not infrastructure errors, so a real remote lookup needs an error-aware contract. Bounded quantity and price prevent overflow. The companion module demonstrates real imports: cmd/demo imports internal/orders and internal/memory; orders never imports the adapter.
Expected output:
600 <nil>unknown itemKeep modules independent of transport
package main
import ( "fmt")
type Inventory struct{ Available int }
func (i Inventory) CanReserve(n int) bool { return n > 0 && n <= i.Available }func label(ok bool) string { if ok { return "accepted" } return "rejected"}func main() { i := Inventory{Available: 3} fmt.Println(label(i.CanReserve(2))) fmt.Println(label(i.CanReserve(4)))}Inventory owns its rule without depending on presentation. A simple layered service with a few packages may suffice for a small application. Use ports for genuine boundaries, and modules when capabilities need independent ownership. More directories do not automatically improve cohesion. A module in this architectural sense is not necessarily a separate Go module (go.mod).
Expected output:
acceptedrejectedTry it locally
Define Tax with Rate() int (0 to 100 percent). Implement FixedTax and total for prices from 0 to 10000 cents, rounding tax down. Print total(1000, FixedTax(5)) and total(101, FixedTax(10)).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Professional architecture 05: Compare layered, hexagonal and modular designs
Check the lesson objective before moving on.
Can a modular monolith use hexagonal architecture?
Which import direction keeps domain rules independent?