Encapsulation
Definition
Encapsulation
- In plain English
- Encapsulation means hiding a type's data and only allowing changes through methods that enforce its rules.
- Think of it like
- It is like a bank teller window where you can't reach into the vault but can ask the teller.
Invariant
- In plain English
- An invariant is a rule about a type's data that must always be true.
- Think of it like
- It is like a lift's rule that it never carries more than eight people.
Why it exists
A caller writes inv.units["O-"] = -5. The next withdrawal fails, but the bad write happened elsewhere. You now have to inspect every assignment.
Route stock changes through a withdrawal method. It checks the amount before changing stock. You know where to find the rule.
How it works
Package
- In plain English
- A package is a group of Go files compiled together that share unexported names.
- Think of it like
- It is like a department in a company that shares an internal notice board.
Exported/unexported
- In plain English
- In Go, a name starting with a capital letter is exported outside its package, while a lowercase name is unexported.
- Think of it like
- It is like a shop’s front counter versus its staff-only back room.
Constructor function
- In plain English
- A constructor function, usually named NewSomething, creates a value that starts in a valid state.
- Think of it like
- It is like buying a kit that comes pre-assembled and ready to use.
- Hide fields
Use lowercase names for state that other packages must not edit.
- Provide NewX
Set up required storage and reject invalid initial inputs.
- Validate changes
Put rules for changing data in the exported methods.
- Expose needed reads
Return copied counts, not the map callers could change.
Another package reaches unexported fields through exported methods. Attempting direct access instead produces a compiler error.
package bloodbank
import "fmt"
type Inventory struct{ units map[string]int }
func NewInventory() *Inventory { return &Inventory{units: make(map[string]int)} }
func (i *Inventory) Add(bloodType string, n int) error {
if bloodType == "" || n <= 0 {
return fmt.Errorf("invalid donation")
}
current := i.units[bloodType]
if current > int(^uint(0)>>1)-n {
return fmt.Errorf("stock overflow")
}
if i.units == nil {
i.units = make(map[string]int)
}
i.units[bloodType] = current + n
return nil
}
func (i *Inventory) Withdraw(bloodType string, n int) error {
if n <= 0 || n > i.units[bloodType] {
return fmt.Errorf("insufficient stock or invalid amount")
}
i.units[bloodType] -= n
return nil
}
func (i *Inventory) Units(bloodType string) int { return i.units[bloodType] }
Examples
Protect the unit count
Inventory owns the unit totals. A request for three units must fail when only two are available.
func ExampleInventory() {
inv := NewInventory()
_ = inv.Add("O-", 2)
err := inv.Withdraw("O-", 3)
// err is non-nil; inv.Units("O-") is still 2.
_ = err
}
Add rejects zero, negative amounts and totals too large for an integer. Withdraw rejects zero, negative amounts and insufficient stock. Units returns a count without sharing the map.
The insight
The invariant lives next to the data it protects.
Extend a stay safely
A guest extends a card's validity, but never past the confirmed checkout time.
package keycard
import (
"fmt"
"time"
)
type KeyCard struct {
room string
validUntil time.Time
}
func NewKeyCard(room string, until time.Time) KeyCard {
return KeyCard{room: room, validUntil: until}
}
func (k KeyCard) Opens(room string, now time.Time) bool {
return k.room != "" && k.room == room && now.Before(k.validUntil)
}
func (k *KeyCard) Extend(by time.Duration, checkout time.Time) error {
next := k.validUntil.Add(by)
if by <= 0 || next.After(checkout) {
return fmt.Errorf("invalid extension")
}
k.validUntil = next
return nil
}
The constructor sets the room and expiry. Callers outside the package cannot move the expiry directly to bypass checkout.
The insight
Hidden fields stop rule-breaking shortcuts.
Add a wrong-PIN lockout
After three wrong PINs, a locker rejects all opening attempts for 15 minutes. Callers keep using Open.
type Locker struct {
pin string
failures int
lockedUntil time.Time
}
func NewLocker(pin string) *Locker { return &Locker{pin: pin} }
func (l *Locker) Open(pin string) error {
now := time.Now()
if now.Before(l.lockedUntil) {
return fmt.Errorf("try later")
}
if !l.lockedUntil.IsZero() {
l.failures = 0
l.lockedUntil = time.Time{}
}
if l.pin == "" {
return fmt.Errorf("locker not configured")
}
if pin != l.pin {
l.failures++
if l.failures == 3 {
l.lockedUntil = now.Add(15 * time.Minute)
}
return fmt.Errorf("wrong PIN")
}
l.failures = 0
return nil
}
func main() {
l := NewLocker("4271")
for range 3 {
fmt.Println(l.Open("0000"))
}
fmt.Println(l.Open("4271"))
}
The insight
Encapsulation lets you add rules later without touching callers.
Trade-offs
Pros
- Checked methods protect the rules from other packages.
- Internals can change without caller edits.
- Failures are easier to trace.
Cons
- Read methods add repetitive code.
- Over-hiding can make tests awkward.
Use when
- Data has rules callers must preserve.
- Several callers change the same state.
Avoid when
- Plain configuration values.
- API request bodies that carry data without behaviour.
Quick check
Takeaways
- Hide data, expose operations.
- Lowercase = package-private in Go.
- Use constructors to set up valid starting values.