【问题标题】:Handling a function call nested within multiple levels of conditionals处理嵌套在多级条件中的函数调用
【发布时间】:2015-06-02 15:50:50
【问题描述】:

基本上,如果满足多个级别的条件,我想展示一些东西。我对 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) ;

【问题讨论】:

  • 在我诚实的观点中,所有 3 个提供的样本都无法维护,从性能的角度来看 2/3,如果在我的诚实意见中是不相关的,那么基于意见的问题在 SO 上是题外话,对不起跨度>
  • InvernoMuto 是正确的,这个问题与本网站无关。如果您可以发布您的实际代码,那么它可能codereview.stackexchange.com 的主题,但您应该在发布之前仔细阅读那里的help section

标签: javascript multiple-conditions indirection


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2018-06-24
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多