OOP Fundamentals • EncapsulationMedium⏱️ ~3 min
Structure: Access Control & Class Design
Encapsulation Structure: A well-encapsulated class has three layers of access control.
BankAccount
- accountNumber: String
- balance: Money
- status: AccountStatus
+ deposit(amount: Money): void
+ withdraw(amount: Money): Result
+ getBalance(): Money
- validateAmount(amount: Money): bool
- updateBalance(delta: Money): void
Access Levels:
First, Private Data (Red): balance, accountNumber, status cannot be accessed from outside. This prevents invalid state like negative balances or unauthorized status changes.
Second, Public Interface (Yellow): deposit(), withdraw(), getBalance() form the contract. These methods enforce business rules and maintain invariants.
Third, Private Helpers (Blue): validateAmount(), updateBalance() are implementation details. They can be refactored without affecting clients.
Method Implementation Pattern:
public withdraw(amount: Money): Result {
// Validate input
if (!this.validateAmount(amount)) {
return Result.failure("Invalid amount")
}
// Check business rule
if (this.balance < amount) {
return Result.failure("Insufficient funds")
}
// Update state through private method
this.updateBalance(-amount)
return Result.success()
}
// Validate input
if (!this.validateAmount(amount)) {
return Result.failure("Invalid amount")
}
// Check business rule
if (this.balance < amount) {
return Result.failure("Insufficient funds")
}
// Update state through private method
this.updateBalance(-amount)
return Result.success()
}
Interview Tip: When designing classes, start by identifying invariants (rules that must always be true), then make all fields private that participate in those invariants.
💡 Key Takeaways
✓Private fields prevent direct manipulation of internal state
✓Public methods form the contract and enforce business rules
✓Private helper methods encapsulate implementation details
✓Validation logic centralizes constraint checking
✓Access modifiers create explicit boundaries between interface and implementation
📌 Examples
1BankAccount ensuring balance never goes negative
2Parking lot ensuring spot capacity is never exceeded
3Library preventing checkout of already borrowed books