Problem Statement
When internal details of a component are exposed, other parts of the system can depend on them directly. This causes bugs when those details change, making the system fragile and hard to maintain.
This diagram shows a client interacting only with the public methods of an encapsulated component, while internal details remain hidden and protected.
### Before (no encapsulation, direct access) class BankAccount: def __init__(self, balance): self.balance = balance account = BankAccount(100) account.balance = -50 # Invalid state allowed ### After (encapsulation and information hiding) class BankAccount: def __init__(self, balance): self.__balance = balance # Private attribute def deposit(self, amount): if amount > 0: self.__balance += amount def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount def get_balance(self): return self.__balance account = BankAccount(100) account.deposit(50) account.withdraw(30) print(account.get_balance()) # Outputs: 120 account.__balance = -50 # Has no effect on actual balance
encapsulation in system design?class Account {
private balance = 1000;
public getBalance() { return this.balance; }
public setBalance(amount) { if(amount >= 0) this.balance = amount; }
}
const acc = new Account();
acc.setBalance(-500);
console.log(acc.getBalance());class User {
public name;
public setName(newName) { this.name = newName; }
}
const user = new User();
user.name = null;
console.log(user.name);name is public, so it can be changed directly without validation.null, bypassing any checks in setName.Pass the test and this pattern moves unknown