Rijalul fikri
Rijalul fikri

Reputation: 41

which is more efficient, simple or nested condition using IF()

I'm newbie, and just want to asking about programming stuff. I hope you guys help me getting understand :)

which is more efficient in coding and performance between this two function? first function using nested condition, and second function using simple condition, which is better to be implemented?

function optionOne()
{
    $a = getData();
    $return = array();

    if ($a === false) {
        $return['error'] = true;
    } else {
        $b = getValue();
        if ($b === false) {
            $return['error'] = true;
        } else {
            $c = getVar();
            if ($c === false) {
                $return['error'] = true;
            } else {
                $return['error'] = false;
                $return['message'] = 'congrat!';
            }
        }
    }

    return $return;
}

function optionTwo()
{
    $return = array();

    $a = getData();
    if ($a === false) {
        $return['error'] = true;
        return $return;
    }

    $b = getValue();
    if ($b === false) {
        $return['error'] = true;
        return $return;
    }

    $c = getVar();
    if ($c === false) {
        $return['error'] = true;
        return $return;
    } else {
        $return['error'] = false;
        $return['message'] = 'congrat!';
    }

    return $return;
}

thank you before guys,

Upvotes: 1

Views: 70

Answers (2)

Deeper
Deeper

Reputation: 129

function option()
{
 $return=array();
 $return['error'] = true;

 switch(getData()){

 case false:
 return $return;
 break;

 case true:
 if(getValue()==false){return $return;}
 else{
 if(getVar()==false){return $return;}
 else{
 $return['error'] = false;
 $return['message'] = 'congrat!';}
 }
 break;

 default:
 return 'getData() return null value';
 break;
 }

}

i was tried to applied the switch method to your function, as one of your option too

Upvotes: 1

sn00k4h
sn00k4h

Reputation: 443

A neater option would be to make the 3 functions throw an exception when there's an error instead of returning boolean false. That's what exceptions are for anyway. Then in your function you can just wrap the calls in a try-catch block.

function option {
  $return = array();
  try {
    $a = getData();
    $b = getValue();
    $c = getVar();

    $return['error'] = false;
    $return['message'] = 'congrat!';
  } catch(Exception e) {
    $return['error'] = true;
  }

  return $return;
}

Upvotes: 0

Related Questions