Garrett Hall
Garrett Hall

Reputation: 30032

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 resizeToFirstCell(Bounds rows, Bounds columns) {
   return rows.set(0, 1) || columns.set(0, 1);
}

Upvotes: 2

Views: 1259

Answers (4)

Scott Urban
Scott Urban

Reputation: 121

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

Upvotes: 3

vivek sapru
vivek sapru

Reputation: 11

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

Upvotes: 1

vcsjones
vcsjones

Reputation: 141668

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

Upvotes: 7

Peter Alexander
Peter Alexander

Reputation: 54280

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

Upvotes: 7

Related Questions