Translate

Saturday 17 February 2024

 What is Encapsulation in Typescript?069

  What is Encapsulation in Typescript?


In TypeScript, encapsulation refers to the concept of bundling data (properties) and related behavior (methods) within a class, while hiding internal implementation details from the outside world. This approach offers several benefits for your code:

1. Data Protection:

  • By keeping properties private, you prevent direct access and modification from external code, reducing the risk of accidental or unintended changes.

  • This ensures data integrity and consistency within the class.

2. Information Hiding:

  • Encapsulation allows you to control how data is accessed and manipulated, providing a layer of abstraction.

  • You can expose data or functionality through public methods, giving you granular control over what external code can interact with.

3. Improved Maintainability:

  • By hiding internal details, you make the code easier to understand and modify.

  • Changes to the internal implementation don't necessarily affect external usage as long as the public interface remains consistent.

4. Reusability:

  • Well-encapsulated classes are more reusable in different parts of your application, as their internal workings are self-contained.

  • You can focus on using the public interface consistently without worrying about internal changes.

Implementation in TypeScript:

  • Access Modifiers: Use private to make properties and methods accessible only within the class, and public to make them accessible from anywhere.

  • Getter and Setter Methods: Provide controlled access to private properties, allowing you to validate or transform data before retrieving or setting it.

  • Interfaces: Define contracts for the public interface of a class, ensuring consistency and decoupling implementation from usage.

Example:


TypeScript

class BankAccount {
  private balance: number;

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

  public deposit(amount: number) {
    this.balance += amount;
  }

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

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

In this example, the balance property is private, ensuring data protection. Only the public deposit and getBalance methods allow controlled access and manipulation.

By embracing encapsulation in your TypeScript projects, you can build more robust, maintainable, and reusable code, enhancing the overall quality and structure of your applications.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.