Encapsulation

Frontend SELF EN
Level 40 , Lesson 2
Available

9.1 Core Concepts

Encapsulation is one of the key concepts of Object-Oriented Programming (OOP), allowing you to hide the internal implementation details of an object and provide access to these details through well-defined interfaces. This helps enhance security and simplifies code management.

Benefits of encapsulation:

  1. Data Hiding: Encapsulation allows you to hide the internal implementation details and provide access only to necessary methods and properties. This prevents incorrect use of objects and improves code security.
  2. Access Control: Encapsulation enables control over access to data and methods, allowing to change the object's internal state only through specified methods.
  3. Maintainability: Encapsulation improves code maintainability as changes in implementation do not affect the external interface of the class. This allows making changes in the implementation without altering the code using the class.
  4. Improved Testing: Encapsulation allows isolating the internal implementation of an object, making unit testing easier and reducing the likelihood of side effects.

In JavaScript, encapsulation is achieved using methods and properties, and starting with ES2022, private fields and methods have also become available.

9.2 Encapsulation with Closures

Before the introduction of private fields in ES2022, encapsulation in JavaScript was often achieved using closures.

Example:

  • The count variable is only accessible inside the createCounter function and is not available from outside
  • The increment, decrement, and getCount methods can interact with the private count variable
JavaScript
    
      function createCounter() {
        let count = 0; // private variable

        return {
          increment() {
            count++;
            console.log(count);
          },
          decrement() {
            count--;
            console.log(count);
          },
          getCount() {
            return count;
          }
        };
      }

      const counter = createCounter();
      counter.increment(); // 1
      counter.increment(); // 2
      console.log(counter.getCount()); // 2
      counter.decrement(); // 1
    
  

9.3 Private Fields in ES2022

ES2022 introduced private fields and methods, which are declared using the # symbol. Private fields and methods cannot be accessed or modified outside the class.

Example:

  • Private fields #name and #age are declared with the # symbol
  • The getName, getAge, setName, and setAge methods allow interacting with private fields
  • Attempting to access private fields from outside the class results in an error
JavaScript
    
      class Person {
        #name; // private field
        #age; // private field

        constructor(name, age) {
          this.#name = name;
          this.#age = age;
        }

        getName() {
          return this.#name;
        }

        getAge() {
          return this.#age;
        }

        setName(name) {
          this.#name = name;
        }

        setAge(age) {
          if (age > 0) {
            this.#age = age;
          }
        }
      }

      const person = new Person('Alice', 30);
      console.log(person.getName()); // "Alice"
      console.log(person.getAge()); // 30
      person.setName('Bob');
      person.setAge(25);
      console.log(person.getName()); // "Bob"
      console.log(person.getAge()); // 25
      
      console.log(person.#name); // Error: private field is inaccessible
    
  

9.4 Private Methods

Private methods can also be declared using the # symbol and be inaccessible from outside the class.

Example:

  • The private field #balance and private method #logTransaction are used to manage the BankAccount object's state
  • The private method #logTransaction is called inside the public deposit and withdraw methods to log transactions
JavaScript
    
      class BankAccount {
        #balance;

        constructor(initialBalance) {
          this.#balance = initialBalance;
        }

        deposit(amount) {
          if (amount > 0) {
            this.#balance += amount;
            this.#logTransaction('deposit', amount);
          }
        }

        withdraw(amount) {
          if (amount > 0 && amount <= this.#balance) {
            this.#balance -= amount;
            this.#logTransaction('withdraw', amount);
          }
        }

        getBalance() {
          return this.#balance;
        }

        #logTransaction(type, amount) {
          console.log(`Transaction: ${type} ${amount}`);
        }
      }

      const account = new BankAccount(1000);
      account.deposit(500); // "Transaction: deposit 500"
      console.log(account.getBalance()); // 1500
      account.withdraw(200); // "Transaction: withdraw 200"
      console.log(account.getBalance()); // 1300
      
      account.#logTransaction('test', 100); // Error: private method is inaccessible
    
  
1
Task
Frontend SELF EN, level 40, lesson 2
Locked
Private fields of Person
Private fields of Person
1
Task
Frontend SELF EN, level 40, lesson 2
Locked
Private Fields in Car
Private Fields in Car
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION