Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
    
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). – David Packer Jun 12 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. – fearless_fool Jun 12 at 14:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.