Builder Pattern

Builder Pattern allows us to build an object with a simpler interface which makes it readable and it benefits a lot if the function/class accepts a lot of arguments.


Imagine we have a backend and we are building the search route. To construct the searching related data, for example, searchTerm, filters, paging, etc. for the database, we can do something like this:

const getQuery(searchTerm, filters, paging)

And we handle the formating implementation in the getQuery()

It might look okay, but we can make it looks cool with the builder pattern.

const query = queryBuilder().setSearchTerm(q).setFilters(filter).setPaging(start, limit).build()

The code formatter with handle the above formatting problem but you get the idea.

  • We have a cleaner interface (readability), the related method is put in one scope (class) and the implementation is separated nicely.
  • Nice to handle lots of moving parts and arguments, we can choose whatever method we want to use to build the ‘object’.

Alternatively in Javascript, we can make use of the javascript object.

function getQuery(searchTerm, {filters, paging} = {})

The interface is also nice with the above one since we are making use of the key-value pair as the argument.

getQuery(q, {filters: filter, paging})



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store