devnotes.

Why Visibility Matters: The Principle of Least Privilege

Access modifiers aren't just syntax — they express a design principle borrowed from security engineering: the principle of least privilege. Every part of a system should have access to only the information and capabilities it strictly needs, and no more.

What goes wrong without disciplined visibility:

class ShoppingCart {
    public items = []       // anyone can push/remove items directly
    public total = 0         // anyone can set an inconsistent total
}

cart = new ShoppingCart()
cart.items.push(newItem)
// Oops — forgot to update cart.total, now it's out of sync with items.
// Nothing in the class prevented this bug.

With everything public, there's no way to guarantee total always reflects the actual sum of items — any code, anywhere, could update one without the other.

With proper encapsulation:

class ShoppingCart {
    private items = []
    private total = 0

    function addItem(item) {
        this.items.push(item)
        this.total += item.price // total is always kept in sync
    }

    function getTotal() { return this.total }
}

Now it's structurally impossible for total to drift out of sync — every path that adds an item also updates the total, because that's the only way to add an item at all.

The practical benefits this produces:

  • Fewer bugs — invalid states become impossible to construct, not just unlikely
  • Safer refactoring — you can freely change how private members are implemented internally, confident that nothing outside the class depends on those details
  • Clearer APIs — a class's public members alone tell you everything you need to know to use it correctly, without reading its internal implementation
  • Easier debugging — when something goes wrong with an object's state, you know it must have happened inside that class's own methods, narrowing the search dramatically

This is precisely why access modifiers, though sometimes seen by beginners as unnecessary ceremony, become indispensable as codebases and teams grow.

Why Access Modifiers Matter in OOP | DevNotes