47

While Sun's Java code convention suggests to put line break before the operator, many other guidelines disagree with it. I do not see any obvious pros and cons. Are there advantages of using one of these styles over the other?

String longVarName = a + b + c + d +
        e + f;

vs

String longVarName = a + b + c + d
        + e + f;
4
  • Can you please post a simple code example showing both conventions?
    – Michael
    Jul 17, 2011 at 14:06
  • First I would try to avoid the situation by using something like this: download.oracle.com/javase/1.4.2/docs/api/java/lang/…
    – Job
    Jul 17, 2011 at 15:13
  • The link is broken.
    – Florian F
    Sep 1, 2014 at 15:42
  • Everyone in replies suggests that such expressions should not happen. However I see a case where there doesn't seem to be a way around: SQL queries. It is very well readable when you write SQL queries in multiple lines. And from my point of view it looks better when "+"s are on the right.
    – Ubeogesh
    Dec 10, 2019 at 12:51

9 Answers 9

17

I'd leave it on one line and rather think about readability in terms of intention-revealing variable names (and functions).

Once it gets messy it's time to refactor:

  • rename variables
  • introduce new variables/functions

Example

subtotal = price * (100 + tax_ratio) / 100

vs.

tax = price * tax_ratio / 100
subtotal = price + tax
5
  • 2
    The formula on the left is incorrect. It should be either price * (100 + tax_ratio) / 100 or just price * (1 + tax_ratio), depending on whether tax_ratio is in percent or fractional.
    – Rufflewind
    Sep 1, 2014 at 17:40
  • 13
    This doesn't answer the question. There should be a law against these type of replies. Mar 23, 2017 at 16:02
  • @EdwardD'Souza I feel the same. But why was the answer accepted? Jun 11, 2019 at 2:32
  • @RudyVissers the answer solves the problem at a deeper level. It solves the problem of needing to line break in the first place. From that perspective, the OP could consider it an answer to his or her problem, but it's still not appropriate from the perspective of this being a community wiki. Jun 11, 2019 at 16:03
  • 3
    hey, I'm not around here anymore but it's really simple - if you find yourself in such situation you're probably doing it wrong and you should rather think about refactoring the code - or to put it otherwise, after 15 ys of programming I simply don't care about such things anymore, what I do care instead is the code clarity, simplicity & making it easy for other people to help me Jun 12, 2019 at 11:47
62

I normally follow the most commonly used style guidelines or a certain coding standard tools. The advantage of using a commonly used style brings benefits when you are reading other people's code or involved in a open source project where a style guidelines are set.

The most common styles that I have seen is the second style in the question. See the below for the list of them:

Google Style Guide:

When a line is broken at a non-assignment operator the break comes before the symbol.

Sun Coding Convention:

Break before an operator

Checkstyle Operator Wrap check's default value is nl:

The operator must be on a new line

2
49

I can imagine readability being an argument

result = longidentifier +
   short -
   alittlelonger -
   c;

versus

result = longidentifier
   + short
   - alittlelonger
   - c;

In the second example the operators are nicely lined up and you can easily see with which sign the variable enters into the equation. I think this also makes sense for binary operators, but with bracing etc., you should just do whatever is clearer.

2
  • 4
    For situations where the operators are important (like math expressions and such) I would choose number two, because, as you said, it is much more readable. But for strings I would choose the first options, as the operators are "meaningless". They don't do anything other than bringing strings together, and because the strings are the important bit, then I would prefer the first options.
    – Niklas H
    Jul 17, 2011 at 14:50
  • Both cases have merit. Both cases are better than putting it all on one very long line! My preference is to to use an opening bracket at the start (even though its not needed) and then having everything line up under that. It makes it far more obvious. Jul 18, 2011 at 9:00
15

In code I tend to put the break after the operator:

foo = some_long_expression() +
      some_other_long_expression();

Here that dangling operator at the end of a line is a big clue to the reader that the code continues. In languages that don't have statement terminators, that dangling operator can serve as a sufficient clue to the compiler/interpreter that the code continues (otherwise I would have to use some ugly continuation line construct).

When documenting that expression (if it needs documentation), I tend to put the break before the operator.

2
  • 1
    At least some languages (e.g. Python) don't take a trailing binary operator as hint that the line continues but require more. Note that newlines inside parens usually aren't counted , so you don't need an explicit (and error-prone) line continuation character.
    – user7043
    Jul 17, 2011 at 15:22
  • 4
    Your big clue is at the end of the line, so I have to read the entire, maybe very long line, all the way to the end to get that glue. It's much faster to look at the beginning of the next line and if it is indented and starts with an operator, I get the same glue, just much faster. So I will usually spot if code is broken among multiple lines before I've even read the first line of it to the end.
    – Mecki
    Apr 22, 2020 at 12:57
4

I believe the line should start with the highest symbol in the parse tree of the statement you want to break. It highlights the operator that is most important in the expression. It is the same reason why you put an else at the begin of a line and not at the end of the previous line.

In the following example, scanning the left margin, you see the structure of the statement as an OR of 3 expressions.

if (ch>='A' && ch<='Z'
    || ch>='a' && ch<='z'
    || ch>='0' && ch<='9')
{...}

Below, the || operators are less highlighted. It is less obvious it is an || of expressions. Especially if the lines were diffent lengths.

if (ch>='A' && ch<='Z' ||
    ch>='a' && ch<='z' ||
    ch>='0' && ch<='9')
{...}

And just for reference, this is very wrong. The || operators are not highlighted at all.

if ( ch>='A' && ch<='Z' || ch>='a'
     && ch<='z' || ch>='0' && ch<='9')
{...}

I even like to put commas at the beginning of the line, even though I seldom see that. I refrain from doing that on shared code.

var note:Object =
    { key: key
    , type: 'P'
    , text: someLongProcedureCallGettingTheUserInitials()
       + ": " + getTheTextThatWasTyped()
    };
3

As long as you remain consistent, then know there's no real advantage either way. This is especially important when considering code merges and white space.

3

Placing the concatenation character (or any operator) at the beginning of the line improves readability. We scan code by focusing on the beginning of each line. When a line starts with an operator, the reader can tell that the line is a continuation of the previous statement by scanning that one character.

Long mathematical expressions are always typeset so that each new line begins with an operator. There is no reason that code should not follow this convention.

0
2

For long arithmetic equations, I typically do one of two things.

leave everything on a single line:

foo = bar + baz - fizz + buzz + alpha - beta;

I typically do this for equations containing only addition and subtraction, i find it very easy to make a typo with multiplication and division that can seriously mess up the scope of the operator.

the second format I use is progressive operators:

foo = bar;
foo += baz;
foo -= fizz;
foo += buzz;
foo /= alpha - beta;
foo *= spiff;

I see no reason to shorten it to a single line, unless it can be proven to improve performance in a noticeable manner. Additionally, there's no ambiguity of what's going on where, and there's less of a chance to misplace a parenthesis for the / and * operators.

1
  • Your two code samples make no difference performance wise as the compiler has to transform the first sample into the second one anyway during compilation.
    – Mecki
    Apr 22, 2020 at 12:58
0

Leave the expression on one line, and if it becomes too long, then break it up into smaller expressions:

days = ((year * months_per_year) + month) * days_per_month + day

becomes:

months = year * months_per_year + month
days = months * days_per_month + day

If this isn't possible, then I find it more readable to break before the operator, and have the operator begin directly below the previous assignment (putting it below the variable makes me have to think and recenter, which is annoying given that the goal is to make things easier to read):

random = years * months_per_year 
         + month * days_per_month 
         + day * hours_per_day 
         + hour * minutes_per_hour 
         + minute * seconds_per_minute 
         + second
1
  • 2
    This answer doesn't add anything new to what has already been said. Sep 2, 2014 at 7:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.