What is the best formatting for operator placement

2019-09-02 15:00发布

问题:

For operations on multiple lines, most of the time, i see and use this formatting:

result = object->someValue() +
    variable -
    function(array) * (arg1 + arg2 + arg3 + arg4);

But i sometimes find this one:

result = object->someValue()
    + variable 
    - function(array) * (arg1 + arg2 + arg3 + arg4);

Same problem for conditions:

if ((conditionA && conditionB) ||
    (conditionC ^ conditionD))

versus

if ((conditionA && conditionB)
    || (conditionC ^ conditionD))

I think the one with operator on newline is more readable, but far less common. Which one would you advise ?

回答1:

I would like to note that this is not necessarily a matter of personal preference. In some languages, it is objectively better to have one style instead of another.

For example, some languages use automatic semicolon insertion. That means that

a = 1 - 2 - 3 -
4 - 5 - 6;

could mean something different than

a = 1 - 2 - 3
- 4 - 5 - 6;

Because the first will be interpreted as

a = 1 - 2 - 3 - 4 - 5 - 6;

But the second could be interpreted as

a = 1 - 2 - 3;
-4 - 5 - 6; //useless expression statement

That means, depending on which style you use, a could be set to either -19 or -4;

In most languages, it doesn't matter, and it really is just a matter of personal preference, but in some languages, such as Javascript, which use automatic semicolon insertion, the first style is preferable.