NYCPHP Meetup

NYPHP.org

[nycphp-talk] Question about explicit returns

Tod Dailey christiandailey at gmail.com
Fri Jan 11 12:45:28 EST 2008


The validity of one of my coding practices that I've used for awhile has
recently come under question. I've tried to listen to arguments on both
sides, and there seems to be good points on both ends, but my question still
hasn't been answered to my satisfaction.

When I'm writing a function that returns a Boolean that indicates that the
given process failed or succeeded, I declare the Boolean as a variable at
the top of the function. I feel that this makes the code easier to read
whenever/if-ever I need to come back and add further logic conditions to
that function. When I come back to the function, I have a short list of
accept by exception where I more-or-less just need to find the point that I
return true to understand the function. Verse inline returns, such as "if
($condition !== true) return false;" that builds a list of failure by
exception. It may just be in my head that the first method is easier to
read, but that's why I'm asking for input/options. Here are two examples.
They should both return the same value, but by different means. Please don't
be side-track by the over-all quality of code/lack-thereof. Thanks!


public function checkForSomething($record_id) {
    $result = false;

    $yourObj = new SomeObject;

    $result = $yourObj->loadObjectByRecordId($record_id);
    if ($result === true) {as
        $restrictedItems = $yourObj->getUnrestictedItems();

        if (is_array($restrictedItems)) {
            $result =
$yourObj->updateUnrestrictedItems(self::ObjectItemStatus);

            if ($result === true) {
                $this->setRecordStatusId($yourObj->getRecordStatusId());
                $this->setRestrictedItemList($restrictedItems);
                $result = true;
            }
        } else {
            $result = false;
        }
    }
}


public function checkForSomething($record_id) {
    $yourObj = new SomeObject;

    if ($yourObj->loadObjectByRecordId($record_id) !== true) {
        return false;
    }

    if (!is_array($restrictedItems = $yourObj->getUnrestrictedItems())) {
        return false;
    }

    if ($yourObj->updateUnrestrictedItems(self::ObjectItemStatus) !== true)
{
        return false;
    }

    $this->setRecordStatusId($yourObj->getRecordStatusId());
    $this->setRestrictedItemList($restrictedItems);
    return true;
}

Once again, this is pseudo-code...
Christian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20080111/d7b10f23/attachment.html>


More information about the talk mailing list