What is preferable: A function that decides itself if it should do anything, or deciding whether to call that function?
function x() {
if ($userIsLoggedIn) {
alwaysHelloUser();
}
if ($visitorRegion != 'US') {
alwaysDisplayNoInternationalShipping();
}
if ($day == 'Sunday') {
alwaysLockDownStore();
}
}
function alwaysLockDownStore() {
//close store
//offer alternative store
//show opening hours
//display form for user leaving order for next day
exit("Sorry, we are closed!");
}
or
function y() {
perhapsSayHelloUser($user);
maybeDisplayNoInternationalShipping($region);
sometimesLockDownStore($day);
}
function sometimesLockDownStore($day) {
if ($day == 'Sunday') {
//close store
//offer alternative store
//show opening hours
//display form for user leaving order for next day
exit ("Sorry, we are closed!");
}
}
The example is trivial, but imagine enabling functions using configuration or access rights. Is there an accepted standard? My gut tells me to go for y()
when there is something like exit()
involved, breaking the normal flow. Otherwise, encapsulation and DRY would favor x()
. What do you think?
Edit I've expended the example. My question is really: If there is a condition on which a function/method should be executed, should that control take place in the function (tidy but outcome is uncertain) or outside it (calling is verbose, but expected output is always the same)?
I'd prefer to keep the main functionality in the function. Extra logic outside. Because the function will do just that what is intented. Or you would everytime run the function needed or not. Depending how complex your problem will be.
function lockStoreOnDay($day) {
// do locking
return "Sorry, we are closed on $day!";
}
echo lockStoreOnDay('Sunday'); //will print "Sorry, we are closed on Sunday!"
echo lockStoreOnDay('Saturday'); //will print "Sorry, we are closed on Saturday!"
Generally: Why not use a Class?
If you have access rights or a configuration this information could be stored in an Array or Object. So you iterate through the Array or search for your keyword and than process whatever should be processed. I. e. make a function call.
function lockStoreOnDay()
{
//do locking
return "Sorry, we are closed!";
}
$config_closeOnDay = array (
'Sunday'
);
foreach ($config_closeOnDay as $dayToCloseOn) {
echo lockStoreOnDay();
}
Maybe this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With