2

I want to avoid using multiples return in my functions, but I can't see how to interrupt them without adding a lot of else in a case like this :

public function foo($number)
{
    if ($number > 8)
    {
        return ' > 8';
    }

    if (exist($number))
    {
        return $number . ' exist';
    }

    return $this->bar($number);
}

My use case is to display an error message for some invalid cases and don't execute what's left in the function.

4
  • What does your last return do, is that an additional validation check? As it looks like you are returning error messages, I would store them all in an error array and return that. Commented Jan 24, 2018 at 14:21
  • @jeroen no, it could be a database manipulation. Commented Jan 24, 2018 at 14:23
  • 1
    The it looks like foo() is doing a bit too much; returning error messages or the result of a separate database operation does not sound very logical and would be hard to process by whatever calls that method. Commented Jan 24, 2018 at 14:24
  • 1
    @jeroen what you've pointed out seems right. In this case foo() can return multiples kind of datas (errors or whatever return bar()). I should split that function. Thanks ! Commented Jan 24, 2018 at 14:37

1 Answer 1

2

You could do something like this:

public function foo($number)
{
    if ($number > 8) {
        $return_value = ' > 8';
    } elseif (exist($number)) {
        $return_value = $number . ' exist';
    }

    return $return_value ?? $this->bar($number);
}

But AFAIK, multiple return are OK, since functions are readable enough. One of my main concern is to have small function, just a few lines, so I don't have to scroll, and I can understand it in seconds. So even if there are three return cases it's still readable.

Sign up to request clarification or add additional context in comments.

2 Comments

But my main concern is to don't trigger $this->bar($number) is one of the condition is met.
Yes, I read it in one of your comments so I fixed it 11 minutes ago. $this->bar($number) is only called if no other condition is met.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.