Rules / Complexity / prefer-conditional-expressions
prefer-conditional-expressions
lint/complexity/prefer-conditional-expressionsrecommended
Same as prefer-conditional-expressions · Dart Code MetricsFlags an if/else whose branches each reduce to a single return or a
single assignment to the same target.
When both branches differ only in the value they return or assign, a
conditional expression — return c ? a : b; or x = c ? a : b; — says the
same thing in one line. The rule reports only the outermost if of a chain
(whose parent is not an if and whose else is not an else if) where both
branches reduce to a single return, or to a single assignment to the same
variable.
Invalid
example.dartdart
// Bad: a single assignment or single return in each branch.
String getStatus(bool isActive) {
if (isActive) {
return 'active';
} else {
return 'inactive';
}
}
int getValue(bool hasValue) {
if (hasValue)
return 42;
else
return 0;
}
class Validator {
bool isValid(String input) {
if (input.isNotEmpty) {
return true;
} else {
return false;
}
}
}
void setLabel(bool on) {
String label;
if (on) {
label = 'on';
} else {
label = 'off';
}
print(label);
}
Prefer a conditional expression over an if/else with a single statement in each branch
2String getStatus(bool isActive) {
3 if (isActive) {
∙
Prefer a conditional expression over an if/else with a single statement in each branch
10int getValue(bool hasValue) {
11 if (hasValue)
∙
Prefer a conditional expression over an if/else with a single statement in each branch
18 bool isValid(String input) {
19 if (input.isNotEmpty) {
∙
Prefer a conditional expression over an if/else with a single statement in each branch
28 String label;
29 if (on) {
∙
Valid
example.dartdart
// Good: cases dart_code_linter's prefer-conditional-expressions does not flag.
String getStatus(bool isActive) {
return isActive ? 'active' : 'inactive';
}
// Branches are calls, not a single assignment or return.
void printMessage(bool success) {
if (success) {
print('Success!');
} else {
print('Failed!');
}
}
// else-if chains are skipped.
String classify(int code) {
if (code == 0) {
return 'zero';
} else if (code == 1) {
return 'one';
} else {
return 'many';
}
}
// Assignments target different variables.
void assignDifferent(bool flag) {
String x = '';
String y = '';
if (flag) {
x = 'a';
} else {
y = 'b';
}
print('$x$y');
}
// Assignment target is not a simple identifier.
void assignIndex(bool flag, Map<String, int> m) {
if (flag) {
m['a'] = 1;
} else {
m['b'] = 2;
}
}
// Multiple statements per branch.
void processData(bool flag) {
if (flag) {
print('Processing...');
final result = compute();
save(result);
} else {
cleanup();
}
}
How to configure
Set the severity of prefer-conditional-expressions in your falcon.json:
falcon.jsonjson
{
"linter": {
"rules": {
"complexity": {
"prefer-conditional-expressions": "error"
}
}
}
}