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