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?)
2