The concept of creating a bundle of some data, allowing its access only through public methods, in order to improve the control over the data policies, states and outcomes. This is commonly done by creating the so called getters and setters functions.

We can say that the object (a class or interface) “knows how” to do things with its own data (properties), and it’s a bad idea for us to access its internals (public properties) and do things with the data ourselves.

If an object doesn’t have an interface method which does what we want to do, we should add a new method or update an existing one.

<aside> 💡 This concept is also often used to hide the internal representation, or state, of an object from the outside.

</aside>

Pros

Code example

Node.js

/**
 * Through encapsulation, we define what our
 * "user" can access and how
 */
class EncapsulationExample {
  private minimum: number = 1000; // User hasn't access to our minimum
  private total: number; // User hasn't access to our total

  constructor() {
    this.total = 0; // set initial state on constructor
  }

  // User can add positive numbers to our total
  public add(value: number) {
    if (!value) return;
    if (value <= 0) return;
    if (isNaN(value)) throw new Error('Value is not valid');

    this.total += value;
  }

  // User can check if its have enough
  public isEnough() {
    return this.total > this.minimum;
  }
}

const example = new EncapsulationExample();
example.add(200);
console.log(`It's enough? `, example.isEnough());
example.add(1000);
console.log(`It's enough? `, example.isEnough());
// console.log(example.total); // It's not going to compile
// console.log(example.minimun); // It's not going to compile