Skip to content

New linter for assignments within conditional expressions #1777

@IndrajeetPatil

Description

@IndrajeetPatil

In the wild, I have come across cases where variables are assigned within conditional expressions and their value is then immediately used as a condition and/or inside their scope. I think this makes the code difficult to understand, and we should lint it.

WDYT?

Here is a reprex with a simple assignment, but you can imagine far more complex assignments and the difficulty to understand the code increases with the complexity of the assignment.

library(lintr)

if (x <- 1L) print(x)
#> [1] 1

# currently, this doesn't generate any lints
lint(
  text = "if (x <- 1L) print(x)",
  linters = linters_with_tags(tags = NULL)
)

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

The suggested alternative here in the lint message would be the following (i.e. do variable assignment outside the expression and then use the variable instead):

x <- 1L
if (x) print(x)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    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