Skip to content

Proposal <switch_on_type> #59546

@FMorschel

Description

@FMorschel

<switch_on_type>

Description

Avoid using switch statements on a Type object. Instead, use type checks with pattern-matching expressions like String _ or int().

Details

Using a switch on a Type 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 Types, promoting more maintainable and safer code.

Bad Examples

void handleType(dynamic variable) {
  switch (variable.runtimeType) {
    case String:
      print('String detected');
    case int:
      print('Integer detected');
    default:
      print('Unknown type');
  }
}

Good Examples

void handleType(dynamic variable) {
  switch (variable) {
    case String _:
      print('String detected');
    case int():
      print('Integer detected');
    default:
      print('Unknown type');
  }
}

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 the runtimeType 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

  • List any existing rules this proposal modifies, complements, overlaps or conflicts with.
  • List any relevant issues (reported here, the [SDK Tracker], or elsewhere).
  • If there's any prior art (e.g., in other linters), please add references here.
  • If this proposal corresponds to [Effective Dart] or [Flutter Style Guide] advice, please call it out. (If there isn't any corresponding advice, should there be?)
  • If this proposal is motivated by real-world examples, please provide as many details as you can. Demonstrating potential impact is especially valuable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3A lower priority bug or feature requestarea-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-linterIssues with the analyzer's support for the linter packagelinter-lint-proposallinter-status-pendingtype-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions