Alternative to nested if for conditional logic

Viewed 7955

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.

3 Answers

All of the foregoing answers seem to miss the question. One of the patterns that frequently occurs in hardware-interface looks like this:

if (something) {
  step1;
  if ( the result of step1) {
    step2;
     if (the result of step2) {
       step3;
     ... and so on
}}}...

This structure cannot be collapsed into a logical conjunction, as each step is dependent on the result of the previous one, and may itself have internal conditions.

In assembly code, it would be a simple matter of test and branch to a common target; i.e., the dreaded "go to". In C, you end up with a pile of indented code that after about 8 levels is very difficult to read.

About the best that I've been able to come up with is:

while( true) {
  if ( !something)
    break;
  step1
  if ( ! result of step1)
    break;
  step2
  if ( ! result of step2)
    break;
  step3
  ...
  break;
}

Does anyone have a better solution?

Related