简体   繁体   中英

Reassigning a boolean if not true

I have a method foo() and foobar() that both return a boolean. Each of them must be executed regardless of the result.

boolean changed = true;
while(changed) {
    changed = foo();
    if(!changed) {
        changed = foobar();
    }
    else {
        foobar();
    }
}

I want the loop to keep executing for as long as changed is true, but I feel like the second code block of ifs and elses for foobar() is not very... elegant. Is there a better way to write that part so that the variable changed will only be reassigned if it's not already true?

Thanks!

How about:

changed = foo() | foobar();

Note the use of the bitwise or operator.

I want the loop to keep executing for as long as changed is true
means? do u want to stop loop if both method returns false if yes then do:

boolean changed = true;
boolean changed1 = true;

    while(changed || changed1) {
        changed = foo();
        changed1 = foobar();
    }

Besides the bitwise OR option, you can also just make sure you put changed second in the expression and all the methods will be executed:

changed = foo();
changed = bar() || changed;
changed = baz() || changed;

I like the bitwise option better since it communicates that the methods have necessary side effects. The above should be well documented to prevent somebody from coming along later and "fixing it to be more performant."

You can use below shortened code styntax

boolean changed = true;
while(changed) {
    changed = (foo())?foobar():(true|foobar());
}

I edited the answer. Thanks all for pointing out the error :)

Basically you want, so long as one of foo() or foobar() return true, to continue executing the loop.

boolean time_to_stop = false;
while (!time_to_stop) {
    boolean foo_result = foo();
    boolean foobar_result = foobar();
    if (false == (foo_result || foobar_result) ) {
        time_to_stop = true;
    }
}

You can shorten this by using syntactically equivalent code structures:

boolean keep_going = true;
while (keep_going) {
    keep_going = foo() | foobar(); 
    // bit-wise OR, avoids compiler short-circuiting optimization
}

To the ultimate short-hand:

while ( foo() | foobar() ) {};

a nice case for using the do-while:

boolean changed;    // no initial value needed
do {
    changed = foo() | foobar();  // should not be ||
} while(changed);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM