1

Is it ok to include a break or exit command to prevent further code from executing or is this bad programming?

function index()
{
  $error = NULL;

  if ($_POST){

     // validate form
    if ($form_validated) {
        echo 'this content only';
        exit;    // or return         IS THIS BAD???
    } else {
        $error = 'form failed';
    }
 }  
  echo 'normal page on initial load';
  if ($error) { echo '<br />'.$error; }
}

2 Answers 2

2

It is OK to prevent further code from executing using exit.

Having said that, whether this is the best way to do it in this particular example is debatable. It is typical to use exit when issuing redirects:

header('Location: /foo');
exit;

In your case, there doesn't seem to be an immediate need to stop the program execution in mid run. You should rather structure your program flow so it always completes, but with different results. It is hard to follow program logic which may terminate somewhere in the middle, so a more logical flow that returns from functions or branches using if..else is usually preferable.

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

Comments

1

For the example you give:

function index()
{
  ...
    if ($form_validated) {
        echo 'this content only';
        exit;    // or return         IS THIS BAD???
    } else {
  ...
}

This is normally called early exit or early return (return is more common). This can be very okay, some people say that early returns make code hard to understand but I'd say it depends on a lot more if a function can be easily read and understood or not.

So the person who decides here whether it is bad or not is you. You need to find some criteria on your own where you draw the line. For example if a function is long (more than 12 lines of code) and contains many of these early returns or even exits, this will make the code more complicated.

Generally early returns can make a functions code less complex which can heavily reduce the number of bugs.

So probably the complexity is a good criteria here.

Additionally I suggest you use exit very carefully. It does much at once and you should normally not need it within your program flow. Especially if you're writing business logic.

Comments

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.