Created
October 19, 2016 07:02
-
-
Save calina-c/96a1e945a55a41cada6db92531df1d92 to your computer and use it in GitHub Desktop.
Exemplified IF inversion technique for better readability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function validateApplicationTangled($user) { | |
if($user->age>18) { | |
if(($user->hasPreviousApplication && !$user->previousApplicationApproved) || !$user->hasPreviousApplication) { | |
printf("Cool, application approved for user %s\n", $user->name); | |
return true; | |
} else { | |
printf("Sorry, but the user %s has a previously approved application\n", $user->name); | |
return false; | |
} | |
} else { | |
printf("Sorry, but the user %s is under 18\n", $user->name); | |
return false; | |
} | |
} | |
function validateApplicationUntangled($user) { | |
if($user->age<18) { | |
printf("Sorry, but the user %s is under 18\n", $user->name); | |
return false; | |
} | |
if($user->hasPreviousApplication && $user->previousApplicationApproved) { | |
printf("Sorry, but the user %s has a previously approved application\n", $user->name); | |
return false; | |
} | |
printf("Cool, application approved for user %s\n", $user->name); | |
return true; | |
} | |
$users = []; | |
class User{}; | |
$users[0] = new User(); | |
$users[0]->age = 20; | |
$users[0]->name = "John"; | |
$users[0]->hasPreviousApplication = true; | |
$users[0]->previousApplicationApproved = false; | |
$users[1] = new User(); | |
$users[1]->age = 16; | |
$users[1]->name = "Emilio"; | |
$users[1]->hasPreviousApplication = false; | |
$users[1]->previousApplicationApproved = null; | |
$users[2] = new User(); | |
$users[2]->age = 22; | |
$users[2]->name = "Trajan"; | |
$users[2]->hasPreviousApplication = true; | |
$users[2]->previousApplicationApproved = true; | |
$users[3] = new User(); | |
$users[3]->age = 22; | |
$users[3]->name = "Klaus"; | |
$users[3]->hasPreviousApplication = false; | |
$users[3]->previousApplicationApproved = null; | |
foreach ($users as $user) { | |
validateApplicationTangled($user); | |
} | |
printf("\n"); | |
foreach ($users as $user) { | |
validateApplicationUntangled($user); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment