-
Notifications
You must be signed in to change notification settings - Fork 28
Description
There is a very popular issue in prettier about putting the operators of multiline binary expressions at the beginning of lines
prettier/prettier#3806
Lots of languages do prefer operators at the beginning, as it improves readability:
prettier/prettier#3806 (comment)
It also has the same benefits of trailing commas, you can often rearrange multiline conditions with a simple copy paste if the operator is leading:
# Start here
this_thing
&& that_thing
&& this_other_thing
# Decide this_other_thing should go second, simple copy paste of the whole line
this_thing
&& this_other_thing
&& that_thing
# Compared to
this_thing &&
that_thing &&
this_other_thing
# Changing to this, which is not a simple copy paste of full lines
this_thing &&
this_other_thing &&
that_thingI tend to agree with the readability argument (the trailing comma argument is less convincing to me), the pep style guide has a good motivating example:
https://peps.python.org/pep-0008/#should-a-line-break-before-or-after-a-binary-operator
# Wrong:
# operators sit far away from their operands
income = (gross_wages +
taxable_interest +
(dividends - qualified_dividends) -
ira_deduction -
student_loan_interest)
# Correct:
# easy to match operators with operands
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)This might be a bit tricky for R code (and maybe for Python?) because at top level or inside { this is invalid R code without being wrapped in () (like in the Python example):
# Invalid R code at top level
income <- gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest
# This works
income <- (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)It's somewhat common to see this kind of thing in if statements (though I'd argue you should create a simpler condition...)
if (
this_thing
&& that_thing
&& this_other_thing
) {
body
}We'd also have to consider pipelines, which are also sequences of binary operators. It's mostly easy with %>% and |>, they just never split this way. But with +? That's tricky because it could be a ggplot2 sequence or just a sequence of arithmetic operations!
# `+` is always trailing here, not leading.
ggplot(data) +
geom_line() +
geom_bar()