System Design Academy

Saving…

Lesson 3 of 10 in Module 10 of 45 lessons complete

Encapsulation

Module 1, lesson 3Concept12 min

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.
  1. Hide fields

    Use lowercase names for state that other packages must not edit.

  2. Provide NewX

    Set up required storage and reject invalid initial inputs.

  3. Validate changes

    Put rules for changing data in the exported methods.

  4. 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.

Other packages reach private state through checked methods.

Another package reaches unexported fields through exported methods. Attempting direct access instead produces a compiler error.

A library package keeps the stock map behind checked operations.
Go
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.

Go fragment: use this inside the bloodbank package.
Go
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.

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

In Go, what makes a field private?
Why did adding the 3-wrong-PINs lockout need no caller changes?

Takeaways

  • Hide data, expose operations.
  • Lowercase = package-private in Go.
  • Use constructors to set up valid starting values.

Try the quick check above whenever you feel ready.

Previous: Types, Structs & Methods