Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How secure a method should be? [closed]

Tags:

javascript

As I am writing some code, I am wondering how secure my methods should be. Should I trust the user of my class ? Or check everything ? This implies parameters type checking which may not be a good practice as Javascript is supposed to be duck typed.

Basically this leads to the question of trust. Is there a best practice ? Is there an implicit "contract" ?

Example :

CarsCollection.prototype.get = function ( index ) {
    return this.collection[index];
};

Or

CarsCollection.prototype.get = function ( index ) {
    var self = this;

    if ( ! index ) {
        throw new ReferenceError();
    }

    if ( isNaN ( index ) ) {
        throw new TypeError();
    }

    return self.collection[index];
};
like image 227
Simon Avatar asked Nov 01 '22 10:11

Simon


1 Answers

You'll find out how robust your methods are by unit testing them. If you write good tests, you'll quickly find that your methods need to be able to handle all kinds of wack input.

It is up to you how far you want to go, but to be clear: don't just assume that the inputs will be valid.

Personally, I validate the hell out of anything that is coming from another class/module/whatever, even if its not third party. You need to make sure that the entry points to each module are robust. I relax a little more within a given class/module, but still make sure to validate enough to prevent errors.

In your sample code, it looks like other pieces of code outside of CarsCollection will be calling the get method. So, you'll want to validate index for sure.

like image 105
lbstr Avatar answered Nov 14 '22 04:11

lbstr