In many cases, it is useful to have a constructor or factory method that validates arguments before instantiating an object, returning a new object if the arguments are valid and null otherwise.

But in traditional javascript constructors, you're limited in what you can return. In particular, you cannot return null.

Is there a preferred programming pattern that accomplishes this, ideally honoring inheritance? Conceptually, I'm looking for something like this (I know this code cannot work):

// This RootClass code can't possibly work -- it's for illustration only
function RootClass() {};
RootClass.prototype.constructor = RootClass;
RootClass.createValidated(arg) {
  return isArgValid(arg) ? originalConstructor(arg) : null;

// example subclass
function OddsOnly(arg) { this._arg = arg; }
OddsOnly.prototype = Object.create(RootClass.prototype);
OddsOnly.prototype.constructor = OddsOnly;
OddsOnly.prototype.isArgValid = function(x) { return x & 1; };

// example calls
var a = OddsOnly.createValidated(3); // => OddsOnly { _arg: 3 }
var b = OddsOnly.createValidated(2); // => null

(Extra credit: is there a way to hide or obfuscate the new method so you must use the createValidated() method?)

  • Have you considered throwing an error on an invalid action as an alternative, effectively terminating the application if a try/catch block is not used and the error properly handled? Although JS is prototype based, throwing constructors are very common among OO languages and I am pretty sure the pattern may be applied to JS too (even more so with ES6, which even supports the class keyword by default).
    – Andy
    Jun 12, 2016 at 11:16
  • @DavidPacker: thank you. Yes, I've considered the throw/catch approach to argument checking. Even though it feels heavy handed, it may be the simplest and ultimately cleanest solution. Jun 12, 2016 at 14:22


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.