If conditions go inside or outside the function / method

Which is preferable: a function that decides itself that it should do something, or a decision to call this 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 that you enable functions using settings or permissions. Is there an accepted standard? My gut tells me to go after y()when there is something like exit()that upsets the normal flow. Otherwise, encapsulation and DRY will contribute x(). What do you think?

. . : , /, (, ) ( , )?

+4
2

. . , . . .

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!"

: ?

, . , , , . I. e. .

function lockStoreOnDay()
{
    //do locking
    return "Sorry, we are closed!";
}

$config_closeOnDay = array (
    'Sunday'
);

foreach ($config_closeOnDay as $dayToCloseOn) {
    echo lockStoreOnDay();
}

, .

+2

, . - :

function isStoreLocked($dayToCheck, $daysLocked)
    {
    // You can replace "locking" logic with database or something
    // There shouldn't be an raw array of days inside code
    return in_array($dayToCheck, $daysLocked);
    }

:

$curentDayName = date('l');
$lockedDays = array('Saturday', 'Sunday');
if(isStoreLocked($currentDayName, $daysLocked))
    {
    die('Sorry, store is locked!');
    }

: ( - Symfony2) isStoreLocked , , Response ( die()).

+1

All Articles