Question

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
  }
  ?>
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top