Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  7] [ 3]  / answers: 1 / hits: 27757  / 14 Years ago, tue, march 1, 2011, 12:00:00

If I have a javascript class which cannot be instantiated what should the constructor return that I can test for. The constructor always returns an object so I cannot return null if the constructor fails.



function SomeClass(id) {
if(typeof(id) === 'number' {
// This is good
this.id = id;
} else {
// This is bad
// This return is ignored and an empty object is returned
return null;
}
}

var a = new SomeClass('badParam');
if(a){
// is true even though the class expects a number.
}

// Could use this check
if(a.id !== undefined){
// Do some stuff
}


but it seems there should be a better way.


More From » class

 Answers
11

It is probably best to throw an exception to notify the caller that the initialization failed and to take appropriate action.



Return codes are fine, but for the most part there is no motivation for the caller to implement the checks on the return code.



My advice is to break hard and break soon. This will make contract violations very evident during testing.


[#93526] Sunday, February 27, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shantelc

Total Points: 737
Total Questions: 120
Total Answers: 104

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
;