mardi 27 janvier 2015

Proper way to refactor multiple if based conditions


I took over a large legacy code base. It has a code like this:



if ($route == 'login' || $route == 'logout' || $route == 'forgot-password') {
return;
}

if ($loggedInUser == false && $currentRoute !== 'login') {
redirectTo('login', 'You need login');
return;
}

if ($loggedInUser) {
if ($loggedInUser['passwordChanged'] == false && $currentRoute !== 'change-password') {
redirectTo('change-password', 'You need change your password');
return;
}

if ($loggedInUser['profileUpdated'] == false && $currentRoute !== 'update-profile') {
redirectTo('update-profile');
return;
}

if ($loggedInUser['role'] !== 'admin') {
redirectTo('logout');
return;
}
}


I think i can make each condition a closure function. Put all of them in an array and loop over array and run each function.


I'm wondering if there is a more elegant way to do this controls.





Aucun commentaire:

Enregistrer un commentaire