-1

基本上,如果满足多个级别的条件,我想展示一些东西。我对 3 种不同方法的性能和可维护性很好奇。:

// 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) ;
}

显示/隐藏可以在嵌套条件的操作之前、期间或之后发生。实际代码有更多级别的条件。我相信您可以提出自己的方法,但我特别询问这 3 种方法的性能和可维护性。我喜欢#3,因为它简短而中肯。要解决invernomuto,请帮助我了解具体的可维护性问题。

方法 1(上)。为每个可能的条件调用“hide_thing()”或“show_thing()”。缺点:每个条件的额外代码。

方法 2. 在开始时调用“hide_thing()”,然后在我希望激活它的特定条件内调用“show_thing()”。缺点:浪费的周期在稍后显示时隐藏事物。

方法 3. 将变量设置为“show_thing”或“hide_thing”,然后通过条件部分之后的变量调用函数。缺点:??

// 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 ;
}

// 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) ;
4

1 回答 1

1

我认为你的第三种方法是三种方法中最好的——第一种方法有很多重复的代码,第二种方法有执行不必要的 UI 操作的风险。但是选项 3 读起来有点混乱,因为show_hide当布尔值更简单时,变量是一个函数。

这个怎么样:

// 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);
}
于 2015-03-29T19:09:20.667 回答