...

/

Factory Pattern: Encapsulation and Simple Code Profiler

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:

Press + to interact
function createPerson (name) {
const privateProperties = {}
const person = {
setName (name) {
if (!name) {
throw new Error('A person must have a name')
}
privateProperties.name = name
},
getName () {
return privateProperties.name
}
}
person.setName(name)
return person
}
const person = createPerson('James Joyce')
console.log(person.getName(), person)

In the preceding code, we leverage a closure to create two objects: a person object, which represents the public interface returned by the factory, and a group ...