Skip to main content

Revealing Design Pattern

Additional Patterns: Revealing Design Pattern


Can you explain the revealing design pattern?

View Answer:
Interview Response: The basic tenet of the Revealing Module pattern is that all functions and variables should be hidden unless explicitly revealed. All of our functions and variables may be defined in the private scope. We can return an anonymous object containing references to the private functionality we want to make public.

Code Example:

// ES2015+ keywords/syntax used: let, const, method declaration, arrow function
// template literals for string interpolation, import, export

let privateVar = 'Ben Cherry';
const publicVar = 'Hey there!';

const privateFunction = () => {
console.log(`Name:${privateVar}`);
};

const publicSetName = (strName) => {
privateVar = strName;
};

const publicGetName = () => {
privateFunction();
};

// Reveal public pointers to
// private functions and properties
const myRevealingModule = {
setName: publicSetName,
greeting: publicVar,
getName: publicGetName,
};

export default myRevealingModule;

// Usage:
import myRevealingModule from './myRevealingModule';

myRevealingModule.setName('Paul Kinlan');