Question

Is it bad programming practice to use the die(); function excessively when validating data in PHP?

I am building a class where I have used that function more than a dozen times, so that if the validation test fails the entire script dies. Is that good practice, is there a better way I should be doing it? Does this practice vary between languages, are there any programming-wide conventions or best-practices to learn from?

Here's an example:

    if($error = $this->checkDate($start)){
        echo "START: ".$error."\r\n";
        die();
    }

    if($error = $this->checkDate($end)){
        echo "END: ".$error."\r\n";
        die();
    }

    if($start>$end){
        $error = "The start date must come <i>after</i> the end date!";
        echo $error;
        die();
    }
    if(($end-$start)<(3*24*3600) || ($end-$start)>(3*30*24*3600)){
        $error = "The period must be at <i>least</i> 3 days long, and at <i>most</i> 3 months long. This date spans about ".round(($end-$start)/(3600*24*30))." months.";
        echo $error;
        die();
    }

etc, etc, etc...

PS - How is "best-practice" not a tag already??

Was it helpful?

Solution

If you are building a bigger system you probably want more output even if it fails, like templating and such. The way you terminate here would make that hard to accomplish in a clean way.

If your application is intended to be really small, so you would not need to do anything after this validation, you are probably good, but then again you should always build code that is easily extendable in case you need to do so later.

If it were up to me, I would probably throw an exception instead and then handle the exception apropriatly at a higher nesting level.

But then again you will need to make the call yourself based on what your actual intent with this application is. Maybe it is appropriate, but probably not.

OTHER TIPS

There are actually two critical flaws in your approach:

  • as a matter of fact, there should be not a single die() statement in the production code.
  • also, no class method should output a word.

Speaking of form validation - your idea of it makes user experience hard and outdated. A good web-site will always show on arror

  • a form itself
  • all the entered data
  • all the errors at once, to let user fix them all, not submit the form again and again until they get to the last error.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top