tidyverse / style

The tidyverse style guide for R code
https://style.tidyverse.org
Other
298 stars 104 forks source link

Allow in-line switch #181

Closed MichaelChirico closed 1 month ago

MichaelChirico commented 2 years ago

Current advice in the guide prevents statements like the following:

units_power <- switch(suffix, k = 1, m = 2, g = 3, t = 4, p = 5)

I think the alternative wastes a lot of real estate:

units_power <- switch(suffix,
  k = 1,
  m = 2,
  g = 3,
  t = 4,
  p = 5
)

The current examples don't address this case specifically... the good example has a fall-through stop, in which case keeping it on its own line is similar to the Control flow recommendations. And once one argument gets its own line, I agree all should.

But also as mentioned, lacking a fall-through stop is OK if the input has been validated (e.g. with match.arg()).

The other non-positional bad examples use fall-through; I agree on using new lines in the fall-through case as well, since it's visually clearer.

That leaves an example like mine: (1) input is pre-validated, so we don't need a fall-through; and (2) all arguments get values.

lorenzwalthert commented 2 years ago

I stand behind the current rules that are idiosyncratic to switch(). They are also consistent with the recommendation for The only case is allow is to put the first argument on a separate line, if it does not fit on the first line.


switch(
  Very_long_stuff_suffix,
  k = 1,
  m = 2,
  g = 3,
  t = 4,
  p = 5
)

For the discussion that lead to the current implementation, see https://github.com/tidyverse/style/issues/39.

hadley commented 2 months ago

I prefer the one-line per argument form, but I agree that if everything can fit on one line, that's also an acceptable styling.