Factory Pattern: Encapsulation and Simple Code Profiler

Learn about the mechanism to enforce encapsulation and build a code profiler.

A factory can also be used as an encapsulation mechanism, thanks to closures. Encapsulation refers to controlling the access to some internal details of a component by preventing external code from manipulating them directly. The interaction with the component happens only through its public interface, isolating the external code from the changes in the implementation details of the component. Encapsulation is a fundamental principle of object-oriented design, together with inheritance, polymorphism, and abstraction.

In JavaScript, one of the main ways to enforce encapsulation is through function scopes and closures. A factory makes it straightforward to enforce private variables. For example, consider the following code:

Get hands-on with 1200+ tech skills courses.