0

I'm constructing a Builder in JavaScript, and I'm not sure how builders normally handle undefined values for optionals. I would like to think that the Builder doesn't append the optional field to the object if the field is undefined. Is that acceptable for a Builder? If not, what would be alternatives?

Here is a sample of the first implementation where the builder doesn't append an undefined optional:

Builder:

function Thing(required1, required2, required3) {
 //check required params 

  var fields = {
    required1: required1, 
    required2: required2, 
    required3: required3
  };  

  var _withOptionalParam = function(param) {
    if(!param) { return this; } //exit function early if param is undefined

    fields.param = param; 
    return this; 
  };

  var _build = function() {
    var result = fields;
    return result;
  };

  var builder = {
    withOptionalParam: _withOptionalParam,
    build: _build
  };

  return builder;
}

In action:

var thing = new Thing("foo","bar","baz").withOptionalParam(undefined).build();

//'thing' should be 
// { 
//  required1:"foo", 
//  required2:"bar", 
//  required3:"baz"
// };
//

Thanks in advance!

  • There's no such thing as an official version of the Builder pattern. Go with whatever makes sense for your application. In terms of options, you have all the options available you can think of (add it, throw an exception, log it, ... ) :-) – Kenneth Jan 14 '16 at 22:24
  • On a side node: `fields.param = param; ` does not do what you think it does. It should probably be `fields[param] = paramValue;` – Kenneth Jan 14 '16 at 22:25

1 Answers1

0

I think you are losing the context of this in your _withOptinalParam function. You could bind you fields object to it as the this context.

function Thing(required1, required2, required3) {
 //check required params 

  var fields = {
    required1: required1, 
    required2: required2, 
    required3: required3
  };  

  var _withOptionalParam = function(param) {
    if(!param) { return this; } //exit function early if param is undefined

    fields.param = param; 
    return this; 
  };

  var _build = function() {
    var result = fields;
    return result;
  };

  var builder = {
    withOptionalParam: _withOptionalParam.bind(fields),
    build: _build
  };

  return builder;
}

var thing = new Thing("foo","bar","baz").withOptionalParam(undefined);

console.log( thing );

//'thing' should be 
// { 
//  required1:"foo", 
//  required2:"bar", 
//  required3:"baz"
// };
//
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
synthet1c
  • 6,152
  • 2
  • 24
  • 39