lundi 23 mars 2015

Checking for valid state inside function or outside


This is a common occurrence in programming and is language agnostic, you have a function that needs to do something but in only in some cases. Maybe it's a feature-toggle, maybe it's a function that needs some data to be passed in to it. You're left with two choices, do you check for that state inside the function, or do you check for that state before you call the function.


I've used javascript as an example.



// method 1 if statement inside function
var getReviews = function() {
if (enabled !== true) { return []; }

var reviews = doWork();

return reviews;
}

var reviews = getReviews();

// method2 if statement outside function
var getReviews = function() {
var reviews = doWork();
return reviews;
}

var reviews = enabled === true ? getReviews() : [];


Pros of check inside:



  • Easy to call, the caller of the function doesn't have to be aware of certain required states, they can simply call, and will get back empty data.


Pros of check outside:



  • If a function is being called when the state is not proper it can raise an exception alerting devs to a possibly bad state, this isn't possible if we silently exit as we do with the check-inside.

  • The function itself is idempotent because it relies on state outside itself. This generally helps with maintainability of functions.





Aucun commentaire:

Enregistrer un commentaire