Question

When writing 'validation code', what is the best way to do it? Like this:

if(!condition1) {
  print('error');
  return false;
}

if(!condition2) {
  print('error');
  return false;
}

do_something();
return true;

Or like this:

if(condition1) {
  do_something();

  if(condition2) {
    return true;
  } else {
    print('error');
    return false;
} else {
    print('error');
    return false;
}

The first way seems cleaner to me, but I'm not sure if there is any advantage / disadvantage of using one method over the other.

Was it helpful?

Solution

Your second function does not do the same as the first, since it runs do_something() even if condition2 is false.

Anyway, I prefer to combine my conditionals, two examples:

if(!condition1 || !condition2) {
  print('error');
  return false;
} else {
  do_something();
  return true;
}

Assuming you want different errors messages:

if(!condition1) {
  print('error1');
  return false;
} elseif(!condition2) {
  print('error2');
  return false;
} else {
  do_something();
  return true;
}

I joined them in an if/elseif chain. It makes your intent clear.

OTHER TIPS

This would be cleaner

$str="";
if(!$condition1){
  $str .="- Error! condition 1 is required.<br>";
}

if(!$condition2){
  $str .="- Error! condition 2 is required.<br>";
}

if(trim($str)!=""){
 print("Error occurred -<br>".$str);
 return false;
}else{
 return true;
}

HOpe this helps

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