2

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.

3
  • So you're asking "Is there an even greater improvement over the status quo shown above than a closure array would be?" But I'm not sure a closure array is an improvement in the first place. What is the measure you're optimizing, readability? That can be had much simpler with a bit of reindenting. – Kilian Foth Jan 27 '15 at 12:23
  • This file has 24 if statements. Some of them are inside other if statements. It's open to errors. I want to learn from more experienced programmers how they handle this situations. – Cnkt Jan 27 '15 at 12:26
  • When comparing the values of the same variable, use a 'switch' statement. – Agi Hammerthief Jan 27 '15 at 20:16
1

Karnaugh Maps are a great way to reduce logic complexity. Karnaugh Maps notwithstanding you want to clearly define the various states and their basic transition logic. Regardless of how much you can reduce the number and complexity of logic expressions you must carefully analyze states (for example "UpdatingProfile") and make methods accordingly.

The closure idea may be fine if your overall design is more functional than object oriented. However it may just be a pointless exercise in sweeping dirt under the rug; Do not make code maintenance worse.

Not the answer you're looking for? Browse other questions tagged or ask your own question.