How to Create Reusable Code in JavaScript Using Design Templates

If you ever want to create reusable JavaScript code or collaborate with a team of developers, you need to know how to use and identify the different design patterns in the language.

In JavaScript, the term design pattern refers to a specific way of writing code and is often considered a programming model. What’s interesting is that the “design template” label can be applied to anything from an entire application to a single block of code.

The design pattern is a huge topic, but by understanding the module pattern and the factory method, you should get used to it.

The module model

JavaScript modules were introduced in 2009, with the ES5 version of the programming language. Using modules, developers could now create custom pieces of code and export them for use in other sections of a JavaScript application.

The basic structure of the module model


(function(){
//Declare private variables and functions
//Declare and return public variables and functions
})();

In the example above, module templates are always included in an immediately invoked function expression (IIFE). This means that a module template is executed as soon as it is defined. The important thing to note is that the module template consists of two separate sections.

The first section is used to declare private variables and functions, which are only accessible as part of the module template.

The second section consists of a return value that contains public variables and functions accessible outside the scope of the module template.

Using the module template to create an application

Consider a simple application such as a task manager. Using the module template, you will need to create custom modules for each section. These may include:

  • A task controller

  • A user interface controller

  • A storage controller

  • An application controller

Related: Programming Projects For Beginners

The task controller will be used to create each new task. The user interface controller will be used to control functions related to the user interface, such as listening for the click of a button or changing what is displayed. The storage controller will be used to record each new task in a database. The application module will be used to run the application.

Using the Module Template to Create a Sample User Interface Controller


const UIController = ( function() {
//the private section of the module
let component="Replacement Text";
const changeComponent = function() {
//change all the h1 text to what is in the component variable above
const element = document.querySelector('h1');
element.textContent = component;
}
//the public section of the module
return{
callChangeComponent: function() {
changeComponent();
}
}
})();

The example above clearly shows the two sections that are in a module template: private and public.

In the private section of the function, the component variable and the changeComponent function are both private. Therefore, if you wanted to change all of the h1 text on a web page, you would get an error if you wrote the following code.

Incorrect way to call the changeComponent example


UIController.changeComponent();

The error message will explicitly state that changeComponent () is not a function of the UIController function. That’s the beauty of the module model; variables and functions created in the private section will never be directly accessible outside the scope of this function.

Although private variables are not directly accessible, they can however be accessed indirectly (from the public section). A takeaway from the UI controller example above is that the public section in the module template is always marked with the return property.

In the parameters of the return property, we can now indirectly access the changeComponent function. We can now use the following line of code (with the module template above) to effectively change all of the h1 text on a targeted webpage to “Alt Text”.

Correct way to call the changeComponent example


UIController.callChangeComponent();

The factory model

Another popular JavaScript design template is the Factory Template (also known as the Factory Method). The module model shines when data encapsulation is required, and the factory model is more useful in cases where we are dealing with a collection of different objects that are similar in some ways.

Coming back to our task manager above; if we were to allow the user to assign a type to each created task, then we could create this aspect of the app (quite efficiently) using the factory template

Using the Factory Template to Assign a Sample Job Type


//Factory pattern function
const TaskFactory = function(){
this.createTask = function(name, type){
let task;
//check the type the user selected
if(type === 'urgent'){
task = new UrgentTask(name);
}else if(type === 'trivial'){
task = new TrivialTask(name);
}
//set the type selected in the if statement to the one received as a property
task.type = type;
//used to print the task and its type to the console
task.define = function(){
console.log(`${this.name} (${this.type}): ${this.priority}`)
}
return task
}
}

The code above uses the factory method to create new jobs, verify the type (urgent or trivial), and assign the appropriate property before printing the new job to the console.

The internal createTask function paves the way for creating multiple tasks at the same time, but before we try to create new tasks, we need to include some additional code in this section of the project.

In the code above, we create a new UrgentTask or a new Trivialtask if a specific condition is met. However, there is no function or class with these names in our project – this problem can be easily solved by introducing the following code into our project.

Create urgent and trivial types of tasks


//Create the urgent task type
const UrgentTask = function(name){
this.name = name;
this.priority = "as soon as possible"
}
//create the trivial task type
const TrivialTask = function(name){
this.name = name;
this.priority = "when you can"
}

Thanks to the code above, we are now able to assign the UrgentTask or TrivialTask ​​property to each new task created. The next step now is to create a new task, but before that we need to create a database to store each new task as it is created.

Since the creation of a database is a separate article, we will replace a database with a data structure (an array).

Creating an example table


//create an array to host the different task
const task = [];

Now we can finally create a new task.

Example of creating new tasks


//create two new tasks
const factory = new TaskFactory();
task.push(factory.createTask('Clean the house', 'urgent'));
task.push(factory.createTask('Reach level 30 in Candy Crush', 'trivial'));

With the code above, you can now create two new tasks using the TaskFactory function that we created initially. When we create each new task, the properties (name and type) are passed to the createTask function, which is in the TaskFactory function that we created using the factory template.

After each task has passed through the TaskFactory and has been assigned the appropriate type property. It is then pushed into the task board we created earlier.

Our only dilemma now is how do we know that these two tasks were created or that our factory model worked? If we had used a database, we could just check the database to see if two new jobs were created.

Go back to the “Use the factory template to assign a task type” example above, just below the comment “used to print the task and its type to the console”, there is a small “task” function .define “that was created to print each table task to the console using the following table method.


//print each task to the console
task.forEach(function(task){
task.define();
});

You should see the following output appear in your console.


Clean the house (urgent): as soon as possible
Reach level 30 in Candy Crush (trivial): when you can

You can now use design templates in your JavaScript projects

At this point, you should understand design patterns in JavaScript and understand how design patterns can be used to create reusable code and make life easier for all developers involved in a project.

Now that you know how two popular JavaScript design patterns work, you should be able to apply them effectively to develop an app.

Image Credit: Alltechbuzz /Pixabay


declare-javascript-variables
How to declare variables in JavaScript

To get started with JavaScript, you need to understand variables. Here are three ways to declare variables in JavaScript.

Read more


About the Author


Source link

Billie M. Secrist

Leave a Reply

Your email address will not be published. Required fields are marked *