lintr
lintr copied to clipboard
Lint LHS literals in conditional expressions?
Preamble
It can be difficult to understand conditional expressions when the numeric, string, etc. literals appear in RHS of the expression, and {lintr}
can help detect such instances.
It's rare to see code like this, so I am wondering if it is worth introducing a new linter, but wanted to create an issue nonetheless.
Examples
Actual
if (0L == length(x)) 1L
if ("a" == x) 1L
if (10L < quantity) discount <- 0.1
...
Suggested/Expected
if (length(x) == 0L) 1L
if (x == "a") 1L
if (quantity > 10L) discount <- 0.1
...
Exceptions
If there are literals on both RHS and LHS. E.g.
dplyr::filter(data, 0L == 1L)
This sounds related to the yoda_test_linter()
. Would it be worth adding this new functionality there (and rename it with a more generic name maybe?)?
You are right! This would be a perfect for that linter. And, yes, we will need to change the name of this linter.
How about yoda_condition_linter()
(https://en.wikipedia.org/wiki/Yoda_conditions)? Generic enough to cover tests, expressions, etc.
yes I had this in mind as going into yoda_test_linter()
This covers a TODO as well:
https://github.com/r-lib/lintr/blob/72eeefd87596ea7fa72ee1a8b14bcb82d322c381/tests/testthat/test-yoda_test_linter.R#L73-L75