JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - Encapsulation

What is Encapsulation?

Encapsulation is a fundamental concept in object-oriented programming that involves bundling the data (variables) and the methods (functions) that operate on the data into a single unit or class. It also restricts direct access to some of an object's components, which is a method of preventing accidental interference and misuse of the state.

Image

Why We Need Encapsulation?

Encapsulation is crucial for several reasons:

  1. Data Hiding: Preventing external parts of a program from directly accessing the internal representation of an object.
  2. Reduce Complexity: By hiding the internal complexity of an object's operations, encapsulation helps to reduce system complexity and increase robustness.
  3. Increase Flexibility and Maintainability: Changes to encapsulated code can be made with minimal impact on other parts of a program. This makes the system more flexible and maintainable.
  4. Controlled Modifications: Encapsulation allows changes to be made in a controlled way. The internal state of an object can only be changed by an object's methods which are predefined.

Example: Accessing and Modifying an Object without Encapsulation

Let’s look at a simple example to understand why encapsulation is needed:

Javascript
Javascript

. . . .

Explanation:

  • The person object stores name and age properties that are publicly accessible and modifiable without any restrictions.
  • Anyone can change the name and age of person without any control, which might lead to inappropriate or erroneous data states.

This lack of encapsulation can lead to problems such as:

  • Security issues: Sensitive data could be exposed or altered inadvertently.
  • Data corruption: Without validation, data can easily be set to invalid or inconsistent states.
  • Harder to debug: Bugs related to unrestricted data modifications can be hard to trace.

Achieving Encapsulation Using Function Closures

In JavaScript, a closure is a function that remembers the environment in which it was created. This feature allows the function to access and manipulate variables that are external to that function, yet local to the scope in which it was defined, long after the outer function has executed.

Closures are a powerful way to achieve encapsulation because they allow you to hide the internal state of the object and expose only what is necessary via the function's return value.

Example: Simple Encapsulation with Closures

This example creates a simple module to manage a user's age with validation, ensuring the age is only updated to valid values, and only retrievable through the module's methods.

Javascript
Javascript

. . . .

Explanation:

  • Function Definition and Initialization:

    • createUser is a function that encapsulates the _age variable. This variable is initialized with the value provided (age) and is hidden from the outside scope, making it private.
    • This function returns an object containing methods getAge and setAge that form the public API for interacting with _age.
  • getAge Method:

    • This method provides read-only access to _age. It returns the current value of _age, allowing it to be accessed but not directly modified from outside the createUser function.
  • setAge Method:

    • Allows controlled modification of _age. It accepts a newAge parameter and includes validation to ensure the age is within an acceptable range (1 to 119 years old).
    • If newAge is valid, _age is updated.
  • Using the Object's Methods:

    • An instance of the user is created with an initial age of 30. The getAge method is called to retrieve and print this age.
    • The setAge method is successfully used to update the age to 35 after validation, and the change is confirmed by calling getAge again.

Achieving Encapsulation Using ES6 Classes and Private Variables

With the introduction of ES6, JavaScript classes became a standard way to achieve encapsulation. ES6 classes allow you to define methods and properties that are neatly encapsulated within class instances.

In addition, JavaScript has introduced syntax for private fields using a hash # prefix, enhancing the encapsulation capabilities by restricting access to these properties from outside the class.

Example: Simple Encapsulation with a Private Field

This example creates a Car class with a private field to store the car's model and public getter and setter methods to access and update the model.

Javascript
Javascript

. . . .

Explanation:

  • Private Field Initialization:

    • #model is a private field in the Car class, initialized through the constructor. This field is not accessible from outside the class, ensuring that the model data is protected and encapsulated.
  • Public Getter Method:

    • getModel() is a public method that allows external code to access the value of the #model field. It simply returns the current value, providing read access to the private field.
  • Public Setter Method:

    • setModel(newModel) is a public method that allows external code to update the value of the #model field. It assigns the new model to the private field, providing a controlled way to modify it.
  • Using the Class:

    • An instance of the Car class, myCar, is created with an initial model of "Toyota Corolla". The model is accessed using the getModel() method and then updated using the setModel() method to "Honda Civic". Subsequent calls to getModel() confirm that the model was successfully updated.

Achieving Encapsulation Using Getters and Setters

Getters and setters are methods used in object-oriented programming to provide controlled access to the properties of an object. In JavaScript, these accessors allow you to define custom logic for getting and setting a property, thus encapsulating and safeguarding the property's value from direct external manipulation.

Example: Simple Encapsulation with Getters and Setters

This example creates a Temperature class that uses getters and setters to manage a temperature property, ensuring that it can be accessed and modified in a controlled manner.

Javascript
Javascript

. . . .

Explanation:

  • Class and Property Initialization:

    • The Temperature class is defined with a private property _celsius, which is intended to hold the temperature in Celsius. This property is initialized via the constructor.
  • Getter Method:

    • The celsius getter provides read access to the _celsius property. When temp.celsius is accessed, this getter is invoked to return the current temperature, thus providing a way to read the temperature without directly accessing the private variable.
  • Setter Method:

    • The celsius setter allows controlled modification of the _celsius property. When temp.celsius is set to a new value, this setter is invoked, updating the temperature. This method provides a way to modify the temperature while encapsulating the logic that might involve validation or notification in more complex scenarios.
  • Using the Class:

    • A Temperature object named temp is created with an initial temperature of 22 degrees Celsius. The current temperature is accessed using the getter and displayed. Then, the temperature is updated to 25 degrees using the setter, and the new temperature is displayed, confirming that the update was successful.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next