2019-09-11
Alternative to nested if for conditional logic
stackoverflow
Question

Is there a design pattern or methodology or language that allows you to write complex conditional logic beyond just nested Ifs?

At the very least, does this kind of question or problem have a name? I was unable to find anything here or through Google that described what I was trying to solve that wasn't just, replace your IF with a Switch statement.

I'm playing around with a script to generate a bunch of data. As part of this, I'd like to add in a lot of branching conditional logic that should provide variety as well as block off certain combinations.

Something like, If User is part of group A, then they can't be part of group B, and if they have Attribute C, then that limits them to characteristic 5 or 6, but nothing below or above that.

Answer
1

The answer is simple: refactoring.

Let's take an example (pseudo-code):

if (a) {
    if (b) {
        if (c) {
             // do something
        }
    }
}

can be replaced by:

if (a && b && c) {
    // do something
}

Now, say that a, b and c are complex predicates which makes the code hard to read, for example:

if (visitorIsInActiveTestCell(visitor) &&
    !specialOptOutConditionsApply(request, visitor) &&
    whatEverWeWantToCheckHere(bla, blabla)) {
    // do something
}

we can refactor that as well and create a new method:

def shouldDoSomething(request, visitor, bla, blabla) {
    return visitorIsInActiveTestCell(visitor) &&
        !specialOptOutConditionsApply(request, visitor) &&
        whatEverWeWantToCheckHere(bla, blabla)
}

and now our if condition isn't nested and becomes easier to read and understand:

if (shouldDoSomething(request, visitor, bla, blabla)) {
    // do something
}

Sometimes it's not straightforward to extract such logic and refactor, and it may require taking some time to think about it, but I haven't yet run into an example which it was impossible.

Alternative to nested if for conditional logic
See more ...