开发者

Is there a pattern or trick to force evaluation on both expressions in an OR conditional statement?

开发者 https://www.devze.com 2023-04-07 02:59 出处:网络
What is the best way (pattern) around return method1() || method2() not invoking method2() if method1() returns true?

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 resizeT开发者_开发百科oFirstCell(Bounds rows, Bounds columns) {
   return rows.set(0, 1) || columns.set(0, 1);
}


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++).


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;
}


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;
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消