Forum Moderators: coopster

Message Too Old, No Replies

Exiting/Entering a function

         

ramoneguru

3:25 am on Aug 27, 2007 (gmt 0)

10+ Year Member



I've always been told that a function should have one exit and one entrance. Lately, I've been seeing code like this:

function foo($temp)
{
if ($temp >= 0)
return true;
else
return false;

}

Nothing really wrong with that only I've been told to do it like this:

function foo($temp)
{
$status = false;
if ($temp >= 0)
$status = true;

return $status;

}

Is there really any significant difference between the two? Any security risks?

--Nick

eelixduppy

3:55 am on Aug 27, 2007 (gmt 0)



>> significant difference

Not much of a difference at all. The first one, in my opinion, is much more readable and the way I would have done it. The second way, while it still does the same thing, makes it a little less obvious what it will return. Both are acceptable.

pinterface

4:21 am on Aug 27, 2007 (gmt 0)

10+ Year Member



I'd write that as:
  function foo($temp) {
return $temp >= 0;
}
, which kinda makes the question moot. ;)

Generally, advice to write code that second way comes from people taking structured programming too far. Going through awful contortions to ensure a function only has one exit point is nuts when multiple exit points make more sense.

For instance, I'd much prefer

  function bar($quux) {
if (some_condition($quux)) return false;
// do other stuff...
return true;
}
over
  function bar($quux) {
if (some_condition($quux)) {
$ret = false;
} else {
// do other stuff...
$ret = true;
}
return $ret;
}
Partially because the first is shorter, but also because it fits how I think about the problem better: "If $quux meets some condition bail out, otherwise do some actual work." versus "Uh, do some stuff, or do some other stuff, then maybe return something.".

ramoneguru

5:03 am on Aug 27, 2007 (gmt 0)

10+ Year Member



Yeah, I figured one was just more structure. Sounds good though, no real significant difference :-)
--Nick