prefer_conditional_expressions
This rule flags an if/else that does nothing but assign or return two values.
Six lines to choose between two strings buries the one thing that varies. A conditional expression puts the choice and both outcomes on one line, and makes it obvious that every path assigns exactly once — which the block form only implies.
Only the two shapes where the rewrite is exact are reported: both branches return, or both assign to the same target with the same operator. A branch with two statements, different targets, different operators, a missing else or an else if chain is left alone, since collapsing it would change what the code does.
This rule is in the pedantic preset.
if (isActive) { label = 'On';} else { label = 'Off';}label = isActive ? 'On' : 'Off';Enabling this rule
Section titled “Enabling this rule”This rule is in the pedantic preset, so it is enabled by preset: pedantic or by name:
rules: prefer_conditional_expressions: enabled: trueTurning this rule off
Section titled “Turning this rule off”To disable this rule:
rules: prefer_conditional_expressions: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_nested_conditional_expressions— Flag a conditional nested inside another.prefer_switch_expression— Suggest converting switch statements to switch expressions.prefer_switch_with_enums— Use a switch instead of an if-else chain over enum constants.avoid_contradictory_expressions— Detect logical AND conditions that always evaluate to false.