\$\begingroup\$
\$\endgroup\$
1
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
shardlshardl
-
1\$\begingroup\$ Your logic flow is easy to follow. No problems here. \$\endgroup\$Drakes– Drakes2015年04月18日 23:47:57 +00:00Commented Apr 18, 2015 at 23:47
2 Answers 2
\$\begingroup\$
\$\endgroup\$
1
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;
-
\$\begingroup\$ Yeah, if you have tons of conditions a
return
statement is your friend, since it has the same net effect as theif
block \$\endgroup\$Machavity– Machavity2015年04月18日 23:47:50 +00:00Commented Apr 18, 2015 at 23:47
\$\begingroup\$
\$\endgroup\$
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
Will AlexanderWill Alexander
lang-php