Coupling & Cohesion
Definition
Coupling
- In plain English
- Coupling is how much one part of the code depends on the details of another part.
- Think of it like
- It is like two train carriages chained together, where a tight chain means one can't move without the other.
Cohesion
- In plain English
- Cohesion is how closely the things inside one type or package belong together.
- Think of it like
- It is like a toolbox holding only plumbing tools instead of a drawer of random items.
Why it exists
You change one line about shelf storage. Five checkout files stop working. Checkout knew too much about shelves.
Ripple effect
- In plain English
- A ripple effect is when changing one piece of code forces changes in many other places.
- Think of it like
- Like a stone dropped in a pond sending rings outward.
You want changes to stay local. Low coupling limits dependencies on details. High cohesion keeps related work together.
How it works
Law of Demeter
- In plain English
- The Law of Demeter says code should talk only to its direct collaborators, not reach through them to their insides.
- Think of it like
- Like asking a shop assistant for milk instead of walking into their stockroom.
| Coupling / cohesion | Low cohesion | High cohesion |
|---|---|---|
| Low coupling | Independent parts with mixed purposes | Target: focused parts with few dependencies |
| High coupling | Mixed purposes and spreading changes | Focused parts that still depend on details |
- Reaching into another type's fields can tie you to its storage choices.
- Long chains such as a.b.c.d expose several layers of details.
- Depending on concrete types everywhere can make replacements harder.
- A util package with unrelated helpers has low cohesion.
- Needing 'and' to describe unrelated jobs suggests a type needs review.
One checkout follows Store, Shelf and Item links. The other checkout asks Store directly through PriceOf.
Examples
Separate unrelated baggage jobs
BagService scans tags, charges excess-weight fees and sends SMS text messages.
Scan reads a bag tag. ChargeFee calculates the fee in this small example; it does not collect payment. SendSMS prints instead of sending a text.
package main
import "fmt"
type BagService struct{}
func (BagService) Scan(tag string) { fmt.Println("scanned", tag) }
func (BagService) ChargeFee(kg int) int { return kg * 5 }
func (BagService) SendSMS(msg string) { fmt.Println(msg) }
func main() {
b := BagService{}
b.Scan("B42")
fmt.Println(b.ChargeFee(3))
b.SendSMS("bag loaded")
}
package main
import "fmt"
type Scanner struct{}
func (Scanner) Scan(tag string) { fmt.Println("scanned", tag) }
type FeeCalculator struct{}
func (FeeCalculator) ChargeFee(kg int) int { return kg * 5 }
type Notifier struct{}
func (Notifier) SendSMS(msg string) { fmt.Println(msg) }
func main() {
Scanner{}.Scan("B42")
fmt.Println(FeeCalculator{}.ChargeFee(3))
Notifier{}.SendSMS("bag loaded")
}
The insight
If you need 'and' to describe unrelated jobs, the type's cohesion may be low.
Hide the shelf arrangement
Checkout reads a price through shelves and items. Reorganising shelves then forces checkout edits.
package main
import "fmt"
type Item struct {
SKU string
Price int
}
type Shelf struct{ Items []Item }
type Store struct{ Shelves []Shelf }
func main() {
store := Store{[]Shelf{{[]Item{{"milk", 120}}}}}
fmt.Println(store.Shelves[0].Items[0].Price)
}
package main
import "fmt"
type Store struct{ prices map[string]int }
func (s Store) PriceOf(sku string) (int, bool) {
price, found := s.prices[sku]
return price, found
}
func main() {
store := Store{map[string]int{"milk": 120}}
price, found := store.PriceOf("milk")
fmt.Println(price, found)
}
The insight
Ask for what you need; do not dig through someone else's storage.
Replace the grab-bag package
A util package holds FormatScore, ParseTeamName, RetryHTTP and HashPassword. Unrelated callers all depend on that package.
FormatScore formats scores, and ParseTeamName reads team names. RetryHTTP repeats failed web requests, while HashPassword transforms passwords for storage. Those jobs belong in separate packages.
Score display, team entry, network calls and sign in all point to the util package.
Score display uses score, team entry uses team, network calls use httpx, and sign in uses auth.
The insight
Grab-bag packages create dependencies between unrelated work.
Trade-offs
Pros
- Changes stay local.
- Focused parts are easier to test.
- People can work in parallel.
Cons
- More small types and files.
- Over-splitting scatters simple logic.
Use when
- Use these goals throughout a growing app.
- Review code when one change spreads widely.
Avoid when
- Do not split a 50-line script into ten packages.
- Do not separate work that always changes together.
Quick check
Takeaways
- Coupling = how much parts depend on each other's details; keep it low.
- Cohesion = how well a type's contents belong together; keep it high.
- Every rule in this module serves those two goals.