开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜