Low-level design2 min

Encapsulation

Encapsulation is one of the four fundamental Object-Oriented Programming (OOP) concepts. It is the mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

Real-Life Analogy

Think of a medical capsule (a pill). The medicine is safely enclosed inside the capsule shell. You don't interact with the chemical powders directly; you swallow the capsule, and it does its job.

Alternatively, think of a bank account. You cannot directly reach into the bank's vault and change your balance from $100 to $1,000,000. Your balance is encapsulated. To change it, you must use public methods provided by the bank (e.g., deposit() or withdraw()). The bank verifies these transactions before updating the internal balance.

How to Implement Encapsulation

To achieve encapsulation:

  1. Declare the variables of a class as private or protected.
  2. Provide public get and set methods (getters and setters) to view and modify the variables.

Example in Code

typescript
class BankAccount {
  // 1. Private data: Hidden from the outside world
  private balance: number;

  constructor(initialBalance: number) {
    this.balance = initialBalance;
  }

  // 2. Public Methods: Controlled access to the data
  public deposit(amount: number): void {
    if (amount > 0) {
      this.balance += amount;
    }
  }

  public withdraw(amount: number): void {
    if (amount > 0 && this.balance >= amount) {
      this.balance -= amount;
    } else {
      throw new Error("Insufficient funds");
    }
  }

  public getBalance(): number {
    return this.balance;
  }
}

// Usage
const myAccount = new BankAccount(100);
myAccount.deposit(50);
console.log(myAccount.getBalance()); // 150

// myAccount.balance = 1000000; // ERROR: Property 'balance' is private

Why is it Important?

  • Control over data: You can make a variable read-only (by providing only a getter) or write-only (by providing only a setter). You can also validate data before allowing modifications (like checking for insufficient funds).
  • Flexibility and Maintainability: The internal implementation of the class can be changed without breaking the code of other classes that use it, as long as the public interface (getters/setters) remains the same.
  • Security: It prevents unauthorized or accidental modification of sensitive data.