dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.27k stars 1.58k forks source link

proposal: `unnecesary_duplicate_value` #59530

Open FMorschel opened 2 months ago

FMorschel commented 2 months ago

unnecesary_duplicate_value

Description

Remove unnecessary ||/&& values to avoid redundancy.

Details

When the || or && operator is used with identical values, leading to redundant code, removing these unnecessary duplicates improves code clarity and reduces potential confusion. By enforcing this lint, developers are encouraged to write more concise and maintainable switch cases, eliminating redundancy without changing the logic of the program. This lint is particularly useful in ensuring that codebases remain clean and that unnecessary conditions do not obscure the intended logic.

Kind

This lint enforces style advice by ensuring more concise and clear code, eliminating redundant conditions in switch cases.

Bad Examples

return switch (value) {
    3 || 3 => 1,  // Lint should trigger here
    _ => 3,
};
if (value == 5 || value == 5) {  // Lint should trigger here
    doSomething();
}
if (value == 5 && value == 5) {  // Lint should trigger here
    doSomething();
}

Good Examples

return switch (value) {
    3 => 1,
    _ => 3,
};
if (value == 5) {
    doSomething();
}

Discussion

Inspired by https://github.com/dart-lang/sdk/issues/59529 for cases of big or expressions where the values might not be exactly side by side and can be hard to spot. Usually, these cases appear when you are doing code refactoring so I believe this could help mainly in those cases.

This could of course have some false negatives but I believe it is best to have some kind of warning than to have none.

If this is ever implemented, I believe this should be added to Effective Dart.

Discussion checklist

FMorschel commented 2 months ago

This would also probably have some relation to unreachable_switch_case and https://github.com/dart-lang/sdk/issues/59529