I've always created javascript objects in the following way:
//object code
function someObject() {
this.field1;
this.fiend2;
}
function makeSomeObject(data) {
var result = new someObject();
result.field1 = data.field1DataName;
result.fiend2 = data.field2DataName;
return result;
}
//object instantiation
var someObject = makeSomeObject(data);
processObject(someObject);
I now want to do this more defensively. In other words I want to test data.field1DataName before setting it. I'm attempting to do this in the following way.
//object code
function someObject() {
this.field1;
this.fiend2;
}
function makeSomeObject(data){
var result = new someObject();
result.field1 = typeof data != "undefined" ? "field1DataNameUndefined": data.field1DataName;
result.field2 = typeof data != "undefined" ? "field2DataNameUndefined": data.field2DataName;
return result;
}
//object instantiation
var someObject = makeSomeObject(data);
processObject(someObject);
Now if a data field is missing that will be caught before the object field is set. The problem is that the someObject
still gets created and processObject
will accept it with out knowing there a problem. My question is what is the best practice for indicating that there's a problem with someObject
so I can avoid problems in processObject
. If anyone has any suggestions for a better practices for defensive programming in javascript in the course of considering this issue that feedback is appreciated as well.