Question

Lets say we have a function, and a caller to that function

function baz(){
    myVar = null;
    foo(myVar);
}

function foo(bar){
    //do stuff
}

where should validation on the parameters happen?

It could be

function baz(){
    myVar = null;
    if(myVar != null){
        foo(myVar);
    }
}

or it could be

function foo(bar){
    if(myVar == null) return null;

    //do stuff
}

What is better? Or if it's situational, when should I use what?

Perhaps an extension of this would also be when should I do

myVar['key'] = myFunc();
function myFunc(){
   return x;
}

vs

myFunc();
function myFunc(myVar){
    myVar['key'] = x;
}
Was it helpful?

Solution

It very much depends. If you are implementing for speed, you may want to consider leavin the choice of validation to the user. If you are implementing for stability, you may want to validate as part of the function.

Imagine an array and the push() function validates. Now imagine using that function a a few hundred times per frame at 60 FPS in a game. That's an extra >6000 if calls per second. Thats a big enough number to matter.

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