Encapsulation and Data Hiding
You'll learn how wrapping data and behavior together—while controlling access—keeps your software safe and predictable.
The Core Idea
Imagine a medicine cabinet in your home. The medicines are stored inside (the data), and there's a childproof lock (controlled access). You don't let anyone reach in randomly and mix medications—instead, you control how and when medicines are accessed. That's encapsulation.
Encapsulation means bundling related data and the methods that work with that data into a single unit (like a class or module). Data hiding means restricting direct access to that data from outside code. Together, they protect your system's invariants—the rules that must always be true for your code to work correctly.
Why This Matters
Without encapsulation, anyone could modify your data in unexpected ways, breaking those critical rules. For example, if you have a bank account balance, you don't want external code directly setting it to -1000 or "apple". Instead, you provide controlled methods like deposit() or withdraw() that enforce the rules: balances can't go negative, inputs must be numbers, etc.
By hiding the internal details and exposing only what's necessary, you create a protective boundary. The outside world interacts through a safe interface, and you're free to change how things work internally without breaking everything that depends on you.
Benefits
- Protects invariants: Rules are enforced in one place
- Reduces coupling: Other code doesn't depend on internal details
- Enables change: You can refactor internals without affecting users
- Improves clarity: Clear boundaries show what's public vs. private
Key Takeaway: Encapsulation bundles data with its operations and hides internal details, creating a protective barrier that maintains system correctness and flexibility.