elegant dice
elegant dice

Reputation: 1337

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.

Upvotes: 2

Views: 2058

Answers (2)

Brian Cray
Brian Cray

Reputation: 1275

There is no reliable getter/setters in javascript right now. You have to check it manually. Here's a way to do that:

if (!('key' in object)) {
    // throw exception
}

Upvotes: 0

Dillen Meijboom
Dillen Meijboom

Reputation: 964

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];
    }
};

Upvotes: 1

Related Questions