What's the proper way to format "if" statements in Java with multiline "ands" or "ors"?

JavaIf StatementFormat

Java Problem Overview


Apparently "if", "and", and "or" are such generic search parameters that I can't find the answer on google for my life. Which of these is the correct format according to the Java standards?

Option 1:

if (condition1
    && condition2
    && condition3) ...

or Option 2:

if (condition1 &&
    condition2 &&
    condition3) ...

Java Solutions


Solution 1 - Java

The Oracle/Sun guidelines ("Code Conventions for the Java TM Programming Language") tell us to break before an operator. And they give this example.

if ((condition1 && condition2)
        || (condition3 && condition4)
        ||!(condition5 && condition6)) {
    doSomethingAboutIt();
} 

Many companies that I've worked for adopt the Oracle/Sun guidelines as the standard for their own code.

Refer http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248

Solution 2 - Java

I believe the correct answer is <CTRL>+<SHIFT>+F in Eclipse :)

Solution 3 - Java

This is completely subjective. Coding standards vary from shop to shop. To steal from yshavit's comment: Do whatever you want unless you are working in a team environment, in which case you should follow the team standards.

I'm a fan of the second pattern.

Solution 4 - Java

This is a preference question. But usually you want to follow the style guidelines of either your company or whoever else is working on the codebase with you. As long as it's consistent, any style is fine.

Personally, I'd keep everything on the same line. (ever dealt with tabs vs. spaces?)

However, if you have enough conditions to fill multiple lines, you should probably break your problem into smaller pieces.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDasmowenatorView Question on Stackoverflow
Solution 1 - JavaDawood ibn KareemView Answer on Stackoverflow
Solution 2 - JavaXuanView Answer on Stackoverflow
Solution 3 - JavaMadConanView Answer on Stackoverflow
Solution 4 - JavayamafontesView Answer on Stackoverflow