Search code examples
javascriptmultiple-conditionsindirection

Handling a function call nested within multiple levels of conditionals


Basically, I want to show something if multiple levels of conditions are satisfied. I'm curious about performance and maintainability of 3 different approaches. :

// Approach 1
if (condition_1) {
   // do_stuff_1 ;
   if (condition_2) {
      // do_stuff_2 ;
      // The crux of the biscuit -- the only time we show the thing.
      show_thing(my_thing) ;
   } else {
      // do_stuff_not_2 ;
      // Hide here ...
      hide_thing(my_thing) ;
   }
} else {
   // do_stuff_not_1 ;
   // ... and hide here
   hide_thing(my_thing) ;
}

The show/hide can happen before, during or after the operations in the nested conditionals. The actual code has more levels of conditionals. I'm sure you can come up with your own approach, but I'm asking specifically about the performance and maintainability of these 3 methods. I favor #3 because it's short and to-the-point. To address invernomuto, please help me understand specific maintainability issues.

Approach 1 (above). Call "hide_thing()" or "show_thing()" for each possible condition. DOWNSIDE: extra code for each condition.

Approach 2. Call "hide_thing()" at the start, then call "show_thing()" within the specific condition where I want it activated. DOWNSIDE: wasted cycles hiding thing when it's later shown.

Approach 3. Set a variable to either "show_thing" or "hide_thing" then call the function via the variable after the conditional section. DOWNSIDE: ??

// Approach 2
// Hide by default
hide_thing(my_thing) ;
if (condition_1) {
   // do_stuff_1 ;
   if (condition_2) {
      // do_stuff_2 ;
      // the only time we show the thing.
      show_thing(my_thing) ;
   } else {
      // do_stuff_not_2 ;
   }
} else {
   // do_stuff_not_1 ;
}

And

// Approach 3
// Indirect show/hide
var show_hide = hide_thing ;

if (condition_1) {
   // do_stuff_1 ;
   if (condition_2) {
      // do_stuff_2 ;
      show_hide = show_thing ;
   } else {
      // do_stuff_not_2 ;
   }
} else {
   // do_stuff_not_1 ;
}
show_hide(my_thing) ;

Solution

  • I think your third approach is the best of the three - the first option has a lot of duplicate code, and the second option risks carrying out unnecessary UI operations. But option 3 is a little confusing to read because the show_hide variable is a function when a boolean is more straightforward.

    How about this:

    // Approach 3
    // Indirect show/hide
    var should_show = false;
    
    if (condition_1) {
       // do_stuff_1 ;
       if (condition_2) {
          // do_stuff_2 ;
          should_show = true;
       } else {
          // do_stuff_not_2 ;
       }
    } else {
       // do_stuff_not_1 ;
    }
    
    if (should_show) {
        show_thing(my_thing);
    } else {
        hide_thing(my_thing);
    }