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 unnecessary_nested_if_linter() #1778

Closed
IndrajeetPatil opened this issue Nov 25, 2022 · 1 comment · Fixed by #1783
Closed

Introduce unnecessary_nested_if_linter() #1778

IndrajeetPatil opened this issue Nov 25, 2022 · 1 comment · Fixed by #1783

Comments

@IndrajeetPatil
Copy link
Collaborator

IndrajeetPatil commented Nov 25, 2022

In the wild (e.g.), I have seen this pattern multiple times: there are nested if() statements, when a single conditional with the right conditional expression would do.

For example, this

x <- TRUE
y <- TRUE

# actual
if (x) {
  if (y) {
    print(1.1)
  }
}
#> [1] 1.1

can be rewritten as:

if (x && y) print(1.1)
#> [1] 1.1

Created on 2022-11-25 with reprex v2.0.2

The benefit is, of course, reduction in complexity and improved readability.

Currently, this doesn't produce a lint:

library(lintr)

code <- "if (x) {
  if (y) {
    print(1.1)
  }
}"

lint(
  text = code,
  linters = linters_with_tags(NULL)
)

Created on 2022-11-25 with reprex v2.0.2


P.S. Needless to say, this is relevant only if there isn't some additional code in the outer scope. E.g.

if (x) {
  y <- x + y
  if (y) {
    ...
  }
}
@MichaelChirico
Copy link
Collaborator

Here's another one to be wary of edge cases, but again I can't seem to recall why :)

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

Successfully merging a pull request may close this issue.

2 participants