Encapsulation

What is Encapsulation?

  • A core concept in OOP

  • Refers to enclosing all the functionality of an object within that object so that the object’s internal workings (its methods and properties) are hidden from the rest of the application

  • This allows us to only we only expose data and functionality that is needed to accomplish such a task and nothing else; this makes your code less prone to errors

  • The means breaking up our classes / objects into two 2 parts

    • Public Interface - what everyone needs to know in order to get our object to accomplish some task

    • Private Interface - the inner workings of the object, the parts that most people don’t see, “under the hood”

  • Real-world Analogy: Cars

    • Public Interface - everything needed to accomplish the core task of getting people from point A to point B; knowledge of how to drive the car, park the car, turn on air conditioning, etc

    • Private Interface - everything “under the hood” or “behind the scenes” necessary for the car to be able to function and provide all of the “features” available in the public interface

Most people know how to operate a car (public interface) but they probably don’t know much about fixing an engine (private interface)


Encapsulation in JavaScript

  • Encapsulation can be achieved with JavaScript Classes by not directly “exposing” instance variables of a Class

  • Example of an “exposed” Class

  // define Car class
  class Car {
    constructor(make, model) {
      this._make = make
      this._model = model
    }
  }

  // create a new instance of the "Car" class
  // and store it in a const variable named "myCar"
  const myCar = new Car("toyota", "prius")

  // changing the "model" instance variable
  // using "direct access"
  myCar._model = "corolla"
  

The example above is not considered best practice because our instance variables are being accessed “outside” of the class; meaning our private data was accessed “publicly”


How do we make instance variables private?

  • Unfortunately, JavaScript does not have built in support for “private” data within object or class

  • The most common way to communicate that an instance variable is private (best practice is to make ALL instance variables private) is to prefix the property with an underscore (_)

  • This is a convention only and does not prevent someone from writing code to access a class’s private data publicly, the instance variables are still technically accessible outside of the class / object, developers will have to rely on our own discipline to do the right thing (until JavaScript implements proper support)

  • The best practice is to provide “indirect” access to your class’s private dat through the use of methods (which we’ll cover next)