I know this can be very use-case specific, but I find myself wondering this far too often. Is there a generally preferred syntax.
I'm not asking what is the best approach when in a function, I am asking should I exit early or should I just not call the function.
Wrap if around function call
if (shouldThisRun) {
runFunction();
}
Have if (guard) in function
runFunction() {
if (!shouldThisRun) return;
}
The latter option obviously has the potential to reduce code duplication if this function is called multiple times, but sometimes it feels wrong to add it in here as then you may be losing the single-responsibility-ness of the function.
Heres an example
If I have an updateStatus() function that simply updates the status of something. I only want the status updated iff the status has changed. I know the places in my code where the status has the potential to change, and I know other places where it definitely has changed.
I'm not sure if its just me but it feels somewhat dirty to check this inside function as I want to keep this function as pure as possible - if I call it I expect the status to be updated. But I can't tell whether it's any better to wrap the call in a check the few places where I know it has the potential to not have changed.