Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

When you\'re in Python or Javascript, you should always put binary operators at

ID: 653055 • Letter: W

Question

When you're in Python or Javascript, you should always put binary operators at the end of the previous line, in order to prevent newlines from terminating your code prematurely; it helps you catch errors.

But in C or C++, this isn't an issue, so I'm wondering:

Is there any reason for me to prefer the second version to the first?

return lots_of_text
       + 1;
versus

return lots_of_text +
       1;
(For example, does one of them help prevent other kinds of errors? Or is one of them considered more readable?)

Explanation / Answer

As you can see from the answers, there is no consensus on this matter. Unless you work in a team, use what you are more comfortable with.

I prefer inserting a newline before operators.

Whenever I have to break lines, I usually put at most one term of the same "level" on a line:

Newton's law of gravitation in Python:

force = (
gravitational_constant
* mass_1
* mass_2
/ (distance * distance)
)
Compare this to:

force = (
gravitational_constant *
mass_1 *
mass_2 /
(distance * distance)
)
I want to know, that I "divide by distance squared", I don't want to know, that "mass_2 gets divided", because that's not how I think of mathematical expressions.

Further, I usually want to know first, what I am doing (operator), before I care about what I do things with (operands).

Or consider this convoluted SQL statement:

WHERE
a = 1
AND b = 2
AND c = 3
AND ( -- or put the OR on one line together with the AND
d = 3
OR e = 1)
AND x = 5
This allows me to see how the individual conditions are connected very easily, just by skimming from top to bottom without having to read every line until the end to find the operator as opposed to:

WHERE
a = 1 AND
b = 2 AND
c = 3 AND
(
d = 3 OR
e = 1) AND
x = 5
I think about the former in terms of "X is true", then I amend that by saying: "AND this is also true" which feels more natural to me than the other way around. Further, I find the first much easier to parse visually.

Or a PHP example:

$text = "lorem ipsum"
. "dolor sit amet, "
. "consectetur adipisicing elit, "
. "sed do eiusmod tempor";
Again, I can just skim read vertically to see I'm simply concatenating text, because most of the time I feel that I do not actually care what is inside the strings/conditions.

Of course, I would not apply this style unconditionally. If putting the newline after an operator seems to make more sense to me, I would do so, but I can't think of an example at the moment.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote