Skip to content

refactor if chains and == with enum values #144903

@nate-thegrate

Description

@nate-thegrate

From the Flutter repo style guide:

Avoid using if chains or ?: or == with enum values


Example (toggle_buttons.dart):

// using "=="
bool _isFirstButton(int index, int length, TextDirection textDirection) {
  return index == 0 && ((direction == Axis.horizontal && textDirection == TextDirection.ltr) ||
    (direction == Axis.vertical && verticalDirection == VerticalDirection.down))
    || index == length - 1 && ((direction == Axis.horizontal && textDirection == TextDirection.rtl) ||
    (direction == Axis.vertical && verticalDirection == VerticalDirection.up));
}


// using a switch statement
bool _isFirstButton(int index, int length, TextDirection textDirection) {
  switch (direction) {
    case Axis.horizontal:
      return switch (textDirection) {
        TextDirection.rtl => index == length - 1,
        TextDirection.ltr => index == 0,
      };
    case Axis.vertical:
      return switch (verticalDirection) {
        VerticalDirection.up   => index == length - 1,
        VerticalDirection.down => index == 0,
      };
  }
}

Performing this refactor would increase the total line length, but in my opinion the improved readability is worth it.

Metadata

Metadata

Assignees

Labels

P3Issues that are less important to the Flutter projectc: proposalA detailed proposal for a change to Flutterframeworkflutter/packages/flutter repository. See also f: labels.r: fixedIssue is closed as already fixed in a newer versionrefactorImproving readability/efficiency without behavioral changesteam-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework team

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions