Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop writing chain code?

for example...

if ( /* Condition */ ) {

    if ( /* Condition */ ) {

        if ( /* Condition */ ) {

          // Superb!

        } else {

          // Error 3

        }

    } else {

      // Error 2

    }

} else {

  // Error 1

}

Do you know how to avoid this? Thank you!

like image 718
Ryan Zygg Avatar asked Nov 24 '10 17:11

Ryan Zygg


Video Answer


2 Answers

If this is a library function, throw may be the appropriate action.

if (!condition1) {
    throw "Condition 1 failed.";
}

if (!condition2) {
    throw "Condition 2 failed.";
}

if (!condition3) {
    throw "Condition 3 failed.";
}

// Superb!

Other acceptable actions might be:

  • Returning 0, null, or undefined.
  • Displaying an error to the user and returning.

You will have to determine which failure action is right for your use case.

like image 73
cdhowie Avatar answered Oct 15 '22 01:10

cdhowie


It looks like you have 3 conditions to check and 4 actions (3 different errors + 1 success). Unfortunately in the general case it's going to require 3 conditional checks and 4 actions. I think the code can be cleaned up a bit by using the following structure though

if (! /* condition 1 */ ) {
  // Error 1
} else if (! /* condition 2 */ ) { 
  // Error 2
} else if (! /* condition 3 */ ) { 
  // Error 3
} else {
  // superb
}
like image 31
JaredPar Avatar answered Oct 14 '22 23:10

JaredPar