Home > Software engineering >  In Java coding convention, for multiline if condition, where to place the logical operators?
In Java coding convention, for multiline if condition, where to place the logical operators?

Time:05-10

In the multiline if condition, I would like to know if we follow a convention where to place the logical operators (&&, ||) or if it's just a preference.

Say we have this kind of if condition below:

Bird bird = new ...; // Some bird species
if (!bird.canFly() && bird.hasWings() && bird.hasFeathers() && bird.canSwim() || ...) {
...
}

With the long if condition above, for readability we just might do a multiline if condition.

For the logical operators, where do we put them? Is it in left or right?

Personally, I'm placing them on the left side so I know which operator is used in the following condition.

Am I doing it right, or wrong?

CodePudding user response:

The official Java SE coding conventions:

4.2 Wrapping Lines:

When an expression will not fit on a single line, break it according to these general principles:

  • Break after a comma.
  • Break before an operator.

So the operator goes to the new line, on the left.

  • Related