优化代码以提高清晰性和效率 [英] Optimizing code for more clearness and efficiency
问题描述
此代码运行良好,但我需要对其进行简化以使其更加清晰并希望提高效率:
This code works fine, but I need to simplify it for more clearness and hopefully more efficiency:
int i = 0;
if (p.cap()) n++;
if (p.creditcard()) n++;
if (p.email()) n++;
[...]
if (p.price()) n++;
if (p.url()) n++;
if (p.zip()) n++;
if (n == 0) p.standard();
正如代码所说,我需要调用多个方法(我不知道它们的数量有限).每个 p.()* 方法都返回一个布尔值,并且 n 仅在返回值为真时递增.如果 n==0(当调用的每个方法都返回 false 时会发生这种情况),那么我需要调用 p.standard().
As the code says, I need to call multiple methods (I don't know the finite number of them). Every p.()* method returns a boolean value, and n is incremented only if the value returned is true. If n==0 (this happens when EVERY method called returns false) then I need to call p.standard().
如何写出更清晰高效的代码?我尝试使用 or 条件,如下所示:
How can I write a more clear and efficient code? I tried with the or condition, something like this:
if (!( p.cap() || p.email() || p.isbn() || p.number() || p.phone() ||
p.price() || p.time() || p.url() || p.zip() || p.creditcard()
)) {
p.standard();
}
但显然它没有正常工作(例如:如果 p.cap() 返回 true,则不会调用其他方法).
But obviously it didn't work properly (example: if p.cap() returns true the other methods are not called).
我需要调用每个方法.
推荐答案
您没有指定是否每个方法都必须被调用,但您似乎想要调用它们而不考虑个别结果.所以使用简单的 or 运算符: |(不是短电路或||).
You did not specify if every method has to be called, but it seems you want to call them all regardless of individual results. So use the simple or operator: | (not the short circuit or ||).
if (!( p.cap() | p.email() | p.isbn() | p.number() | p.phone() |
p.price() | p.time() | p.url() | p.zip() | p.creditcard()
)) {
p.standard();
}
这篇关于优化代码以提高清晰性和效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!