Object Oriented Programming: Encapsulation

William W
2 min readFeb 18, 2021

This is a short glossary entry on encapsulation. Encapsulation is a fancy word for data hiding. Data hiding is fancy talk for building code so that someone can just type English words to use it, lowering the chance that people use your code wrong.¹

Here’s an example in Javascript you can run right now:

Created in JSBin

Console.log is a print debugging function in Javascript. In this example, we declare a new variable called “person.” Then, we define attributes like firstName, lastName, and favoriteFood. We also assign values to those attributes. For instance, the “lastName” attribute has the value “Doe”, a 3 character string.

Notice how we also defined our last attribute “fullName” by using a function that combines the first two attributes: “firstName” and “lastName.” We also save an outside user from having to do this every time by putting it in the var declaration.

So where is the encapsulation? Well, by defining these attributes ahead of time, we can just make calls in the format: “person.[whatever attribute].” In this case, the “person” variable is also an object.²

So a new user or developer (or even another piece of code) can make simple calls to an object instead of needing to go into the definitions. It also prevents users from changing the properties of the person to something invalid: for instance, changing a name to a number.³

  1. The actual definition in Wikipedia is closer to “Hiding the values or state of a structured data object inside a class, preventing direct access to them by clients in a way that could expose hidden implementation details or violate state invariance maintained by the methods.” But that’s a very unhelpful description for beginners.
  2. Technically, everything is an object in Javascript. Data typing is achieved by creating further instances of an object under the hood. This is why you’ll often see [object Object] when printing your data.
  3. We didn’t actually set controls for this in our example. We simply disallowed the user from changing the data within the person object altogether by not providing a “setter” method. If we wanted to, we could create a function that rejects strings with invalid characters, then use that for a proper “setter” method, allowing a user to set a name without needing to worry about whether it’s valid or not.

--

--

William W

Electrical Engineering. Software developer and cofounder of a startup.