是否有一种模式或技巧来强制评估OR条件语句中的两个表达式?

Gar*_*all 2 c# c++ java design-patterns

如果返回,return method1() || method2()不调用的最佳方式(模式)是什么?method2()method1()true

我正在使用这个类绑定一个表:

class Bounds {
    // return true iff bounds changed
    boolean set(int start, int end);
}
Run Code Online (Sandbox Code Playgroud)

我希望此函数调整行和列的大小,并返回true iff被修改:

public boolean resizeToFirstCell(Bounds rows, Bounds columns) {
   return rows.set(0, 1) || columns.set(0, 1);
}
Run Code Online (Sandbox Code Playgroud)

vcs*_*nes 7

使用非短路(有时称为"Eager")运算符|.

public boolean resizeToFirstCell(Bounds rows, Bounds columns) {
    return rows.set(0, 1) | columns.set(0, 1);
}
Run Code Online (Sandbox Code Playgroud)

你可以阅读更多有关的在操作文档||(C#具体环节,但对于Java和C++依然如此).

  • @gordatron:你是对的,它们是用于按位操作.我相信C++,这可以通过首先将bool推广到int(false = 0,true = 1)然后对这些int进行按位OR来实现.我认为它在C#和Java中是相同的.它有点hacky,但它有效,并且在性能敏感的代码中使用了很多,其中分支由于&&和|| 很贵. (2认同)
  • 请注意,这不完全相同......它假设`set`返回一个`bool`(或0/1).@Scott Urban的解决方案通常是一种更可靠的模式,而且更容易阅读.(如果你坚持这个快捷方式,`!! rows.set()| !! columns.set()`是一个可靠的模式.) (2认同)
  • @gordatron:是的,`!!`是"不是不是".它将零映射到零,非零映射到一,这是你需要使用逻辑"|"的一般情况.(所以它不仅仅是一个提示......`x || y`和`x | y`通常计算不同的东西.` !! x | !! y`计算与`x || y`相同的东西但是没有短路.)但同样,@ Scott Urban的回答同样正确,同样快速,易于阅读.从各方面来说,它确实是一个更好的答案.(另请注意,此答案不一定保留评估顺序.) (2认同)

Pet*_*der 7

public boolean resizeToFirstCell(Bounds rows, Bounds columns) {
    // Intermediate values are used to explicitly avoid short-circuiting.
    bool rowSet = rows.set(0, 1);
    bool columnSet = columns.set(0, 1);
    return rowSet || columnSet;
}
Run Code Online (Sandbox Code Playgroud)

  • 它不是理解编程语言,而是更多关于不实现`columns.set(0,1)`*must*execute;) (3认同)