-
Notifications
You must be signed in to change notification settings - Fork 1.7k
proposal: no_else_after_return
#59148
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I think typically I would advocate that the former (bad) example is more readable in many cases. In cases where a return is an early return that allows 100 lines following to be not indented 2 spaces, it makes sense to not use Also, as this is a style suggestion, I think we need such a rule to be backed by a style guide, like Effective Dart. |
jfyi, if you decide not to add this rule to the linter, it's already available in DCM https://dcm.dev/docs/rules/common/avoid-redundant-else/ |
Drive-by comment: It sounds like this lint could be quite useful. It also reminded me of the idea that some language constructs could announce that "if we reach this point, we're done". Cf. dart-lang/language#3080. The point is that it is then very easy to see at a glance that a given if-statement is guaranteed to end the execution in the current function body, and this again provides a guarantee (at a glance) that the code that comes after the if-statement will be executed if and only if we would have executed an |
I'm with @srawlins. I prefer the "bad" example most of the times. Obviously, there are cases where the readability is worse, specially as we increase the nesting of the condition. However, most cases I see are just like the example: String something(bool condition) {
if (condition) return 'Something';
return 'Not something';
} Using |
I think about this every time I have conditional logic that returns on both branches. I tend to lean towards the early return style suggested here, but I'm never fully convinced that it is actually better. I do appreciate the symmetry of having the returns in both branches at the same level. I think this would be a reasonable lint to support but only if users have to explicitly opt in to enable it if they prefer that style and want consistency. I don't think we'd want "Effective Dart" to have an opinion one way or the other. I just don't think it matters enough either way to be worth bothering users. |
no_else_after_return
Description
Move the code of the else branch below the
if
block.Details
When the
if
case always ends with areturn
, the else branch is not necessary and the code can instead be placed below theif
block. This decreases code complexity and indentation and overall improves readability.Kind
style advice, maybe?
Bad Examples
Good Examples
Discussion
Real world example: flutter/flutter#126935 (comment)
Discussion checklist
The text was updated successfully, but these errors were encountered: