Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce a linter to encourage using value matching instead of chained equality checks? #2379

Closed
IndrajeetPatil opened this issue Dec 2, 2023 · 2 comments

Comments

@IndrajeetPatil
Copy link
Collaborator

Preamble

The following two code snippets are equivalent in many scenarios. But the value matching operator (%in%) approach is generally preferable for its readability (more concise) and maintainability (as values to check grows, the vector can easily be expanded) over the chained equality checks approach. Of course, this is relevant only if there are more than one comparison in the chain.

Example that should produce lint

Using chained equality checks

library(lintr)

'if (x == "a" || x == "b" || x == "c") {
  message("abc")
} else {
  message("not abc")
}' -> code

lint(text = code, linters = all_linters())

Created on 2023-12-02 with reprex v2.0.2

Example that shouldn't produce a lint

Using value matching operator

if (x %in% c("a", "b", "c")) {
  message("abc")
} else {
  message("not abc")
}

Edge cases

  • If x is missing (NA), %in% will return FALSE, whereas the chained equality approach will fail.
  • x can be a vector in the chain (e.g. if (any(x == c("a", "b")) || any(x == c("c", "d"))) { ... }). Such cases won't be relevant for this linter.
@Bisaloo
Copy link
Contributor

Bisaloo commented Dec 2, 2023

Is this #1875?

@IndrajeetPatil
Copy link
Collaborator Author

Indeed! I had a hunch that we had discussed this here before but just couldn't find the issue.

Closing in favour of that issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants