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?
Here is an example in JavaScript to illustrate what I mean:
// method 1 if statement inside function
var getReviews = function() {
if (enabled !== true) { return []; }
return doWork();
}
var reviews = getReviews();
// method2 if statement outside function
var getReviews = function() {
return doWork();
}
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.
This question mainly stems from worrying about maintenance so I will make an assumption that you are going to have many of these state-dependent functions.
I would recommend having a layer in between your client and the function that it is calling which is state dependent. Then let this layer handle the state management. This will do two things for you:
1) Offload the logic from your client and from your function.
2) Centralize all of your state management in one place instead of having it all over the place outside of functions or inside of each individual function.
If you are checking states inside of your functions you are adding more responsibility to what they already are doing and therefore violating the single responsibility principle.
Additionally, you are scattering your state logic all over the place (whether you check inside or outside) instead of having it in one centralized place – As you have mentioned yourself, this is a maintenance nightmare as your functions start to add up and you decide to make a change.