0

This is more or less a readability, maintainability and/or best practice type question.

I wanted to get the SO opinion on something. Is it bad practice to return from multiple points in a function? For example.

<?php

  // $a is some object

  $somereturnvariable = somefunction($a);

  if ($somereturnvariable !== FALSE) {
        // do something here like write to a file or something
  }

  function somefunction($a) {
        if (isset($a->value)) {
              if ($a->value > 2) {
                    return $a->value;
              } else {
                    return FALSE;
        } else {
              // returning false because $a->value isn't set
              return FALSE;
        }
  }
  ?>

or should it be something like:

<?php

  // $a is some object

  $somereturnvariable = somefunction($a);

  if ($somereturnvariable !== false) {
        // do something here like write to a file or something
  }

  function somefunction($a) {
        if (isset($a->value)) {
              if ($a->value > 2) {
                    return $a->value;
              } 
        } 

        return FALSE
  }
  ?>
au_stan
  • 3,551
  • 2
  • 16
  • 24
  • In this situation I would go with second version, as it's more readable. Of course, if you would need to return more than two possible values, second way is not possible. – Daniel Cisek May 03 '13 at 18:34
  • Looks like a great [codereview](http://codereview.stackexchange.com/) question... – Brad Christie May 03 '13 at 18:36
  • true... but than i have to create another username and have to go to multiple sites for questions... ain't no body got time for that. – au_stan May 03 '13 at 18:41

1 Answers1

1

As a matter of practice, I always try to return from ONE point in any function, which is usually the final point. I store it in a variable say $retVal and return it in the end of the function.It makes the code look more sane to me.

Having said that, there are circumstances where say, in your function as the first line you check if a var is null and if yes you are returning. In this case, there is no point in holdin on to that variable, then adding additional checks to skip all the function code to return that in the end.

So...in conclusion, both ways works. It always depends on what the situation is and what you are more comfortable with.

raidenace
  • 12,380
  • 1
  • 27
  • 33
  • plus, returning earlier would mean you dont need to process the code below the return if it is already evaluated as true.. – reikyoushin May 03 '13 at 18:41
  • @reikyoushin: Exactly.. In lengthier code it would be just a waste and makes the function messy with additional checks. – raidenace May 03 '13 at 18:42
  • ok sounds good to me. i just found myself writing similar style functions in different projects either one way or another. more or less depending on my mood at the time. i wanted to end the internal debate :D – au_stan May 03 '13 at 18:43