具有共同逻辑的条件:风格问题、可读性问题、效率问题、
我有条件逻辑,需要对每个条件(实例化对象、数据库查找等)通用的预处理。我可以想到 3 种可能的方法来做到这一点,但每种方法都有一个缺陷:
选项 1
if A
prepare processing
do A logic
else if B
prepare processing
do B logic
else if C
prepare processing
do C logic
// else do nothing
end
选项 1 的缺陷是昂贵的代码是多余的。
选项 2
prepare processing // not necessary unless A, B, or C
if A
do A logic
else if B
do B logic
else if C
do C logic
// else do nothing
end
选项 2 的缺陷在于,即使 A、B 或 C 都不成立,昂贵的代码也会运行
选项 3
if (A, B, or C)
prepare processing
end
if A
do A logic
else if B
do B logic
else if C
do C logic
end
选项 3 的缺陷在于 A 的条件、B、C 被评估两次。评估的成本也很高。
现在我想了一下,选项 3 有一个变体,我称之为选项 4:
选项 4
if (A, B, or C)
prepare processing
if A
set D
else if B
set E
else if C
set F
end
end
if D
do A logic
else if E
do B logic
else if F
do C logic
end
虽然这确实解决了 A、B 和 C 的昂贵评估问题,但它使整个事情变得更加复杂。丑陋,我不喜欢它。
您如何对这些选项进行排序?还有其他我没有看到的选项吗?
I have conditional logic that requires pre-processing that is common to each of the conditions (instantiating objects, database lookups etc). I can think of 3 possible ways to do this, but each has a flaw:
Option 1
if A
prepare processing
do A logic
else if B
prepare processing
do B logic
else if C
prepare processing
do C logic
// else do nothing
end
The flaw with option 1 is that the expensive code is redundant.
Option 2
prepare processing // not necessary unless A, B, or C
if A
do A logic
else if B
do B logic
else if C
do C logic
// else do nothing
end
The flaw with option 2 is that the expensive code runs even when neither A, B or C is true
Option 3
if (A, B, or C)
prepare processing
end
if A
do A logic
else if B
do B logic
else if C
do C logic
end
The flaw with option 3 is that the conditions for A, B, C are being evaluated twice. The evaluation is also costly.
Now that I think about it, there is a variant of option 3 that I call option 4:
Option 4
if (A, B, or C)
prepare processing
if A
set D
else if B
set E
else if C
set F
end
end
if D
do A logic
else if E
do B logic
else if F
do C logic
end
While this does address the costly evaluations of A, B, and C, it makes the whole thing more ugly and I don't like it.
How would you rank the options, and are there any others that I am not seeing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你做不到吗
?也许我误解了。
编辑:zzz,你的编辑搞乱了我。如果你不想让它评估 A、B、C 两次,那么就这样做
Can't you do
? Maybe I misunderstood.
Edit: zzz, your edits messed me up. If you don't want it to evaluate A,B,C twice then do
这不是解决了冗余问题吗:
Doesn't this solve the redundancy: