Question

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.

No correct solution

OTHER TIPS

This is how I normally do it, with some sort of extend method, and a .defaults = {} object, jQuery's works in this case.

function SomeObject(data) {
    $.extend(this, SomeObject.defaults, data);
}

SomeObject.defaults = {
    field1: '',
    field2: ''
};

var newObject = new SomeObject({ field1: 'field1' });

console.log(newObject);
// > { field1: 'field1', field2: '' }

You could say that we have defined a default mixin for SomeObject, since we are $.extending this. This way we can let $.extend handle the null/undefined checks.

As far as handling errors in the object you can initialize your defaults to null and throw new Error() when something is not passed in.

function SomeObject(data) {
    $.extend(this, SomeObject.defaults, data);
    if (this.field1 == null) {
        throw new Error('SomeObject: field1 is required');
    }
}

SomeObject.defaults = {
    field1: null,
    field2: null
};

var newObject = new SomeObject({ field2: 'field2' });
// > Error: SomeObject: field1 is required

Two great articles about throwing errors

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top