Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should conditions go inside or outside of function/method [closed]

Tags:

php

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)?

like image 604
PeerBr Avatar asked Jan 22 '14 13:01

PeerBr


1 Answers

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.

like image 84
Ben Avatar answered Nov 15 '22 22:11

Ben