Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Builder pattern in javascript
Meysam Faghfouri
Meysam Faghfouri

Posted on • Edited on

     

Builder pattern in javascript

One of the most used patterns in the software development world is Builder pattern which is under the Creational category of design patterns.

The philosophy of this pattern is to separate between an object and its creating process especially for those objects which are complex and need more steps and complex validations to be created so we need to breakdown these steps and transfer them into another place. By doing so, we can have more control over the object's creation process and the validity of it, and more importantly, we will have a simple code to test and read and maintain.

Another benefit that we can get from this pattern is that by using it, as we decoupled the higher-level components from the object's direct constructor, in case of needing to add or remove steps to the process of building we can do it in just one single point, and we don't have to worry about the different ways of creating the object in different components.

Let's get started with a very simple code in javascript. Consider bellow code:

varPersonBuilder=(function(){_person={};//Imagine this is a complex object and needs a variety of validationsfunctionPersonBuilder(){};//constrcutorPersonBuilder.prototype.setName=function(name,family){if(!name)thrownewError('Parameter "name" should not be null');if(!family)thrownewError('Parameter "family" should not be null');_person.name=name;_person.family=family;returnthis;};PersonBuilder.prototype.setAge=function(age){if(age<=0)thrownewError('Age is not valid');_person.age=age;returnthis;};PersonBuilder.prototype.checkPersonValidation=function(){if(_person.age==undefined)thrownewError("the Age of the person has not been set. Please use 'setAge' before getting the person object");if(!_person.name||!_person.family)thrownewError("the name and family of the person have not been set. Please use 'setName' before getting the person object");};PersonBuilder.prototype.getPerson=function(){this.checkPersonValidation();return_person;};returnPersonBuilder;}());
Enter fullscreen modeExit fullscreen mode

Now we have:

letbuilder=newPersonBuilder();builder.setAge(30);builder.setName("foo","fighters");//Or we can use it as chaining way like thisbuilder.setAge(30).setName("foo","fighters");letperson=builder.getPerson();console.log(person)/* {  age: 30,  family: "fighters",  name: "foo"}*/
Enter fullscreen modeExit fullscreen mode

If you use invalid parameters or skip one of those steps you will get this result for example:

letbuilder=newPersonBuilder();builder.setAge(30);letperson=builder.getPerson();//Uncaught Error: the name and family of the person have not been set. Please use 'setName' before getting the person object"
Enter fullscreen modeExit fullscreen mode

Of course, the 'person' here is an elementary object because I kept this in this way for the sake of simplicity but when the destination object is complex, this pattern will become very handy.

I hope you now have a better understanding of this pattern and please leave a comment if you have any suggestion.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I love coding and creating cool things using different tools. and I'm always interested in learning
  • Location
    Iran
  • Education
    Bachelor of Information Technology
  • Work
    Fullstack. NET Developer at Telecommunication Company of Iran
  • Joined

More fromMeysam Faghfouri

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp