Skip to content

proposal: unneccessary_ternary_operator #58954

Open
@jacob314

Description

@jacob314

unneccessary_ternary_operator

Description

Unnecessary ternary operator. Same result can be achieved with less code.

Details

A search of Dart code in g3 shows 150 cases where people have written the pointless ternary operator code in Dart:
foo ? true : false instead foo
and 70+ cases of
foo ? false : true instead !foo

Likely code reviewers caught even more cases before the code was committed.
Quick assists to refactor if / else to use ternary operators can accentuate the number of uncaught versions of this unnecessarily verbose code as see in For example, flutter/devtools#4890 caught one such case.

Give a detailed description that should provide context and motivation. Ideally this could be used directly in the rule's documentation.

Kind

This enforces

Bad Examples

bool baz() => foo ? true : false;
bool bar() => foo ? false : true;

Good Examples

bool baz() => foo;
bool bar() => !foo;

Discussion

I wouldn't have thought this lint would be needed but I missed catching an example like this after applying automated fixes to a code base and the g3 codebase has 158 examples of ? true : false and 75 examples of ? false : true so users do make this mistake in practice likely when refactoring code and forgetting to fully simplify the code.

Discussion checklist

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3A lower priority bug or feature requestarea-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-linterIssues with the analyzer's support for the linter packagelinter-lint-proposallinter-status-pendingtype-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions