Skip to content

Introduce unnecessary_nested_if_linter() #1778

Description

@IndrajeetPatil

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) {
    ...
  }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions