Skip to contents

Avoid unnecessary nested if conditional statements

Usage

unnecessary_nested_if_linter()

See also

linters for a complete list of linters available in lintr.

Examples

# will produce lints
writeLines("if (x) { \n  if (y) { \n   return(1L) \n  } \n}")
#> if (x) { 
#>   if (y) { 
#>    return(1L) 
#>   } 
#> }
lint(
  text = "if (x) { \n  if (y) { \n   return(1L) \n  } \n}",
  linters = unnecessary_nested_if_linter()
)
#> ::warning file=<text>,line=2,col=3::file=<text>,line=2,col=3,[unnecessary_nested_if_linter] Don't use nested `if` statements, where a single `if` with the combined conditional expression will do. For example, instead of `if (x) { if (y) { ... }}`, use `if (x && y) { ... }`.

# okay
writeLines("if (x && y) { \n  return(1L) \n}")
#> if (x && y) { 
#>   return(1L) 
#> }
lint(
  text = "if (x && y) { \n  return(1L) \n}",
  linters = unnecessary_nested_if_linter()
)

writeLines("if (x) { \n  y <- x + 1L\n  if (y) { \n   return(1L) \n  } \n}")
#> if (x) { 
#>   y <- x + 1L
#>   if (y) { 
#>    return(1L) 
#>   } 
#> }
lint(
  text = "if (x) { \n  y <- x + 1L\n  if (y) { \n   return(1L) \n  } \n}",
  linters = unnecessary_nested_if_linter()
)