2
\$\begingroup\$

When developing API methods to return JSON with details I often find myself creating the following code:

 $response = array('success' => false);
 $user = User::getSessionUser();
 if($user->id > 0){
 if(ItemSKU::stringIsValid($sku)){
 $itemSKU = ItemSKU::getFromString($sku);
 if($itemSKU->isAvailable()){
 if(Carts::add($user->id, $sku)){
 $response['success'] = true;
 }
 else{
 $response['error'] = "Item was already added";
 }
 }
 else{
 $response['error'] = "Unavailable Item";
 }
 }
 else{
 $response['error'] = "Invalid SKU";
 }
 }
 else{
 $response['error'] = "Invalid User";
 }
 return response()->json($response);

How can I avoid using this nested if-else chain?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Apr 18, 2015 at 23:41
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Your logic flow is easy to follow. No problems here. \$\endgroup\$ Commented Apr 18, 2015 at 23:47

2 Answers 2

4
\$\begingroup\$

Personally I prefer avoiding such nested if-else constructs, simply by reversing the logic, e.g.:

if(!cond1)
 return value;
if(!cond2)
 return value2;
// etc.

instead of:

 if (cond1)
 if(!cond2)
 return value2;
 else
 return value;
answered Apr 18, 2015 at 23:45
\$\endgroup\$
1
  • \$\begingroup\$ Yeah, if you have tons of conditions a return statement is your friend, since it has the same net effect as the if block \$\endgroup\$ Commented Apr 18, 2015 at 23:47
0
\$\begingroup\$

You can check for the error conditions first, and immediately return if they're true:

$response = array('success' => false);
$user = User::getSessionUser();
if(!($user->id > 0)){
 $response['error'] = "Invalid User";
 return response()->json($response);
}
if(!ItemSKU::stringIsValid($sku)){
 $response['error'] = "Invalid SKU";
 return response()->json($response);
}
$itemSKU = ItemSKU::getFromString($sku);
if(!$itemSKU->isAvailable()){
 $response['error'] = "Unavailable Item";
 return response()->json($response);
}
if(Carts::add($user->id, $sku)){
 $response['success'] = true;
}
else{
 $response['error'] = "Item was already added";
} 
return response()->json($response);
answered Apr 18, 2015 at 23:55
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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