是否有某种模式或技巧可以强制对 OR 条件语句中的两个表达式进行求值?

发布于 2024-12-06 12:47:56 字数 485 浏览 1 评论 0原文

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

示例

我使用此类来绑定表:

class Bounds {
    // return true iff bounds changed
    boolean set(int start, int end);
}

并且我希望此函数调整行和列的大小,并在任一被修改时返回 true:

public boolean resizeToFirstCell(Bounds rows, Bounds columns) {
   return rows.set(0, 1) || columns.set(0, 1);
}

What is the best way (pattern) around return method1() || method2() not invoking method2() if method1() returns true?

Example

I'm using this class to bound a table:

class Bounds {
    // return true iff bounds changed
    boolean set(int start, int end);
}

and I want this function to resize both the rows and columns and return true iff either was modified:

public boolean resizeToFirstCell(Bounds rows, Bounds columns) {
   return rows.set(0, 1) || columns.set(0, 1);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

笑脸一如从前 2024-12-13 12:47:56

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

public boolean resizeToFirstCell(Bounds rows, Bounds columns) {
    return rows.set(0, 1) | columns.set(0, 1);
}

您可以在操作员文档< /a> 代表 || (C# 特定链接,但对于 Java 和 C++ 仍然适用)。

Use a non-short circuiting (sometimes called "Eager") operator, |.

public boolean resizeToFirstCell(Bounds rows, Bounds columns) {
    return rows.set(0, 1) | columns.set(0, 1);
}

You can read more about that in the operator documentation for || (C# specific link, but still holds true for Java and C++).

一场春暖 2024-12-13 12:47:56
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;
}
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;
}
空气里的味道 2024-12-13 12:47:56

这是一个可以很好地扩展更多语句的“模式”:

bool fun() {
    bool changed = false;
    changed |= rows.set(0, 1);
    chnaged |= columns.set(0, 1);
    return changed;
}

Here's a "pattern" that scales well for more statements:

bool fun() {
    bool changed = false;
    changed |= rows.set(0, 1);
    chnaged |= columns.set(0, 1);
    return changed;
}
木有鱼丸 2024-12-13 12:47:56

请使用 |急切求值而不是短路运算符 http://en.wikipedia.org/wiki/Short- Circuit_evaluation

Please use the | eager evaluation instead of shortcircuit operator http://en.wikipedia.org/wiki/Short-circuit_evaluation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文