elegant dice elegant dice - 7 months ago 14
Javascript Question

How to prevent access to object properties that do not yet exist

Often I have this situation:

var obj = { field: 2 };


and in the code:

do_something( obj.fiel ); // note: field spelt wrong


ie The property is incorrectly typed. I want to detect these bugs as early as possible.

I wanted to seal the object, ie
obj = Object.seal(obj);


But that only seems to prevent errors like
obj.fiel = 2;
and does not throw errors when the field is simply read.

Is there any way to lock the object down so any read access to missing properties is detected and thrown?

thanks,
Paul

EDIT: Further info about the situation


  1. Plain javascript, no compilers.

  2. Libraries used by inexperienced programmers for math calc purposes. I want to limit their errors. I can spot a misspelt variable but they can't.

  3. Want to detect as many errors as possible, as early as possible. ie at compile time (best), at runtime with thrown error as soon as wrong spelling encountered (ok), or when analysing results and finding incorrect calculation outputs (very very bad).

  4. Unit tests are not really an option as the purpose of the math is to discover new knowledge, thus the answers to the math is often not known in advance. And again, inexperienced programmers so hard to teach them unit testing.


Answer

I don't think this will work in Javascript since objects are written like JSON and thus properties will be undefined or null but not throw an error.

The solution will be writing a native getter/setter.

var obj = {
    vars: {},

    set: function(index, value) {
        obj.vars[index] = value;
    },

    get: function(index) {
        if (typeof(vars[index]) == "undefined") {
            throw "Undefined property " + index;
        }

        return vars[index];
    }
};