DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Mastering React App Configuration With Webpack

Trending

  • Software Delivery at Scale: Centralized Jenkins Pipeline for Optimal Efficiency
  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  • Advancing Robot Vision and Control
  • A Guide to Auto-Tagging and Lineage Tracking With OpenMetadata
  1. DZone
  2. Coding
  3. JavaScript
  4. Builder Pattern in Javascript

Builder Pattern in Javascript

Initialize objects with more human-readable code in a few, simple steps.

By 
Souradip Panja user avatar
Souradip Panja
·
Sep. 12, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
14.6K Views

Join the DZone community and get the full member experience.

Join For Free

legos-scattered-on-wooden-floor

For those who don't care about code readability: step on a lego

Suppose we go to a store and want to buy a product. Let’s say a PC. We have two options; either buy a ready-made PC of any particular brand, or we customize and assemble it.

In this scenario, we go for the second option — we will collect different parts and construct a new PC.

You may also like: Design Patterns for Beginners With Java Examples.

Now, the person who is building the PC is basically the builder who knows which part to assemble to make it the computer functional. This person in terms of design patterns is known as the Builder pattern.

A Builder pattern is generally in charge of:

  • Simplifying the construction of an object.

  • Separating the construction and representation of that object.

  • Composition.

  • Creating different representations for the constructed object.

Let’s take a simple example

Course.js

class Course { 
  constructor(name, sales, isFree = false, price, isCampain = false) { 
    this.name = name; 
    this.sales = sales || 0; 
    this.isFree = isFree; 
    this.price = price || 0; 
    this.isCampain = isCampain;  // Advertising Campaign 
  } 
  
  toString() { 
    return console.log(JSON.stringify(this)); 
  } 
}

module.exports = Course; 


main.js

const Course = require('./course');  
  
const course_1 = new Course('Design Patterns 1', 0, true, 149 , true);  
const course_2 = new Course('Design Patterns 1', 0,false, 0, false);  
  
course_1.toString();  
course_2.toString();  


Now, if anyone observes this line,

const course_1 = new Course('Design Patterns 1', 0, true, 149 , true); 


will they be able to say what 0, true, 149, true signifies? Surely not. They have to go to the Course class constructor every time to see what value each parameter is tied to.

This problem can be easily solved by the Builder pattern. If the above line is represented in builder pattern, then it will look like

const course_1 = new CourseBuilder('Design Patterns 1').makePaid(100).makeCampain().build();  


Here, one can easily tell what parameters are required for the class.

Let’s build this above example with a builder pattern

  • Create a file for the builder (e.g. Coursebuilder.js)
  • Create a constructor with the parameter required. Use default values for best practice.
  • Create a function with meaningful names for the parameters used in the constructor.
  • Return the values used within the function. (i.e return this).
  • Create a method that will return the instance of the class for which the Builder class is made. In our example, we are creating a builder pattern for Course, so we will make a function that will return instance of the Course class with the values. We'll name it build().

CourseBuilder.js

const Course = require('./course');  
  
class CourseBuilder{  
    constructor(name, sales = 0, price = 0){  
        this.name = name;  
        this.sales = sales;  
        this.price = price;  
    }  
  
    makePaid(price){  
        this.isFree = false;  
        this.price = price;  
        return this;  
    }  
  
    makeCampain(){  
        this.isCampain = true;  
        return this;  
    }  
  
    build(){  
        return new Course(this);  
    }  
}  
  
module.exports = CourseBuilder;  


Now, in the main file instead of Course class, import the Coursebuilder class. Then, create an instance of it.

Main.js

const CourseBuilder = require('./CourseBuilder');  
  
//const course_1 = new CourseBuilder('Design Patterns 1', 0, true, 149 , true);  
//const course_2 = new CourseBuilder('Design Patterns 1', 0,false, 0, false);  
const course_1 = new CourseBuilder('Design Patterns 1').makePaid(100).makeCampain().build();  
const course_2 = new CourseBuilder('Design Patterns 2').build();  
  
course_1.toString();  
course_2.toString();  


Here, we can see that in the Builder pattern, the object creation code is less error-prone, as users will have a clear understanding of what parameters they are using.


Related Articles

  • Module Pattern in JavaScript. 
  • Domain-Driven Design in JavaScript. 

Builder pattern JavaScript

Opinions expressed by DZone contributors are their own.

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Mastering React App Configuration With Webpack

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!