Proposal <avoid_switch_on_runtimeType
>
#59546
Labels
analyzer-linter
Issues with the analyzer's support for the linter package
area-analyzer
Use area-analyzer for Dart analyzer issues, including the analysis server and code completion.
linter-lint-proposal
linter-status-pending
P3
A lower priority bug or feature request
type-enhancement
A request for a change that isn't a bug
<
avoid_switch_on_runtimeType
>Description
Avoid using switch statements on an object's
runtimeType
. Instead, use type checks with pattern-matching expressions likeString _
orint()
.Details
Using a switch on
runtimeType
can lead to bad code that is prone to breaking when class hierarchies change or new types are added. This approach is not type-safe and doesn't take advantage of Dart’s strong static typing system. Instead, it's better to leverage more robust alternatives such as pattern matching (switch with exhaustiveness over sealed types) to handle multiple types in a type-safe manner.Kind
Guard against errors: This lint guards against the misuse of a switch on
runtimeType
, promoting more maintainable and safer code.Bad Examples
Good Examples
Discussion
The inspiration comes from #56763 and #59087.
This is motivated by cases like the SDK issue above where at the Discord discussion previous to it the user was using
runtimeType
on the switch creating some confusion as to how to use switch patterns. Since in most cases, the user is not trying to actually switch on theruntimeType
anymore now that we have expression matching like the above, it should probably be safe for us to call out on that.If this lint passes, I believe it should probably be under Effective Dart.
Discussion checklist
The text was updated successfully, but these errors were encountered: