Skip to content

New linter to suggest moving complex conditional expressions to boolean function/variable? #1830

@IndrajeetPatil

Description

@IndrajeetPatil

Preamble

Complex conditional expressions can make the code difficult to read because they interrupt the "flow" of the main program.

If one instead extracts them to a boolean function/variable, the new conditional expression much more readable and, as a side effect, the new function/variable introduces a reusable abstraction in the codebase.

Example

Actual

if (looks_like_a_duck(x) && 
    swims_like_a_duck(x) && 
    quacks_like_a_duck(x)) {
  ...
}

Suggested-1: boolean function

is_duck <- function(x) {
  looks_like_a_duck(x) &&
    swims_like_a_duck(x) &&
    quacks_like_a_duck(x)
}

if (is_duck(x)) {
  ...
}

Suggested-1: boolean variable

is_duck <- 
  looks_like_a_duck(x) &&
  swims_like_a_duck(x) &&
  quacks_like_a_duck(x)

if (is_duck) {
  ...
}

Note that this is the simplest cases, but one can imagine that the expression depend on different objects, and so the boolean function can be multi-parameter (e.g. is_duck(x, y, z)).

Configurable

As for what constitutes a complex conditional expression can be configurable. The default will be 2L. That is, any expression with more than two operands will set off this linter. But users can set this to a higher or a lower value (e.g. if someone prefers to always use a boolean function in a conditional expression to improve readability).

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions