GAZAR

Principal Engineer | Mentor

Encapsulating Variables: Best Practices with TypeScript

Encapsulating Variables: Best Practices with TypeScript

Encapsulation is a fundamental concept in object-oriented programming that involves bundling data and methods that operate on that data into a single unit, known as a class. By encapsulating variables within classes, developers can control access to the data and enforce rules for its manipulation, leading to more robust and maintainable code. In this article, we'll explore best practices for encapsulating variables in TypeScript, along with examples to illustrate these concepts.

Example: Encapsulating Variables in TypeScript

class BankAccount {
  private balance: number;

  constructor(initialBalance: number) {
    this.balance = initialBalance;
  }
  getBalance(): number {
    return this.balance;
  }
  setBalance(newBalance: number): void {
    if (newBalance >= 0) {
      this.balance = newBalance;
    } else {
      throw new Error("Invalid balance value");
    }
  }
}
const account = new BankAccount(1000);
console.log(account.getBalance()); // Output: 1000
account.setBalance(1500);
console.log(account.getBalance());

Encapsulating variables using access modifiers, accessors, and related data grouping is a foundational practice in object-oriented programming. By following best practices for encapsulation, developers can create more maintainable, reliable, and secure TypeScript codebases. Encapsulation promotes data integrity, facilitates code reuse, and improves overall software quality.


Comments