What is an acceptable way to format a long method call in Java?

Willi Mentzel picture Willi Mentzel · Jun 25, 2015 · Viewed 7.6k times · Source

Is it good style to write:

objectName.methodWithManyParameters(someLongParameter1, someLongParameter2, someLongParameter3, someLongParameter4, someLongParameter5);

(which is obviously far to long for one line) as

objectName.methodWithManyParameters
(
    someLongParameter1, 
    someLongParameter2, 
    someLongParameter3, 
    someLongParameter4, 
    someLongParameter5
);

Another way would be:

objectName.methodWithManyParameters(someLongParameter1, someLongParameter2, 
                                    someLongParameter3, someLongParameter4,
                                    someLongParameter5);

Answer

Jordi Castilla picture Jordi Castilla · Jun 25, 2015

According to Oracle 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.
  • Prefer higher-level breaks to lower-level breaks.
  • Align the new line with the beginning of the expression at the same level on th previous line.

If the above rules lead to confusing code or to code that's squished up against the right margin, just indent 8 spaces instead.

Here are some examples of breaking method calls:

someMethod(longExpression1, longExpression2, longExpression3, 
        longExpression4, longExpression5);


Resuming

Second option is the standard convention, first is more readable, but can harm in really long methods or if many calls because of the lenght of the classes...