Grouping conditional operators

is there a way to group conditional operators in an if statement?

something like this:

    if (obsticle.x > 980 && (rightPaddle.y < obsticle.y < rightPaddle.y+200))
    {

    xi *= -1;
     }
   obsticle.x = obsticle.x + (1*xi);

the goal is if obsticle.x is between the two numbers then it will change directions. if not it will continue unchanged.

You could group all your conditions in a method that returns a bool, ex

bool inRange() {
    return (obsticle.x > 980 && (rightPaddle.y < obsticle.y < rightPaddle.y+200));
}

and then use this method whenever you need in your code, ex

if (inRange()) {
    xi *= -1;
}

Obviously inRange is a silly name, something that has to do with the logic of your app would have more sense.
In this way you separate the decision about the behaviour and the behaviour itself, and you improve the readability of your code.

1 Like