pattern-matching refactor (#154753)

This pull request aims to improve code readability, based on feedback gathered in a recent design doc.

<br>

There are two factors that hugely impact how easy it is to understand a piece of code: **verbosity** and **complexity**.

Reducing **verbosity** is important, because boilerplate makes a project more difficult to navigate. It also has a tendency to make one's eyes gloss over, and subtle typos/bugs become more likely to slip through.

Reducing **complexity** makes the code more accessible to more people. This is especially important for open-source projects like Flutter, where the code is read by those who make contributions, as well as others who read through source code as they debug their own projects.

<hr>

<br>

The following examples show how pattern-matching might affect these two factors:

<details> <summary><h3>Example 1 (GOOD)</h3> [click to expand]</summary>

```dart
if (ancestor case InheritedElement(:final InheritedTheme widget)) {
  themes.add(widget);
}
```

Without using patterns, this might expand to

```dart
if (ancestor is InheritedElement) {
  final InheritedWidget widget = ancestor.widget;
  if (widget is InheritedTheme) {
    themes.add(widget);
  }
}
```

Had `ancestor` been a non-local variable, it would need to be "converted" as well:

```dart
final Element ancestor = this.ancestor;
if (ancestor is InheritedElement) {
  final InheritedWidget inheritedWidget = ancestor.widget;
  if (widget is InheritedTheme) {
    themes.add(theme);
  }
}
```

</details>

<details> <summary><h3>Example 2 (BAD) </h3> [click to expand]</summary>

```dart
if (widget case PreferredSizeWidget(preferredSize: Size(:final double height))) {
  return height;
}
```

Assuming `widget` is a non-local variable, this would expand to:

```dart
final Widget widget = this.widget;
if (widget is PreferredSizeWidget) {
  return widget.preferredSize.height;
}
```

<br>

</details>

In both of the examples above, an `if-case` statement simultaneously verifies that an object meets the specified criteria and performs a variable assignment accordingly.

But there are some differences: Example 2 uses a more deeply-nested pattern than Example 1 but makes fewer useful checks.

**Example 1:**
- checks that `ancestor` is an `InheritedElement`
- checks that the inherited element's `widget` is an `InheritedTheme`

**Example 2:**
- checks that `widget` is a `PreferredSizeWidget`
(every `PreferredSizeWidget` has a `size` field, and every `Size` has a `height` field)

<br>

<hr>

I feel hesitant to try presenting a set of cut-and-dry rules as to which scenarios should/shouldn't use pattern-matching, since there are an abundance of different types of patterns, and an abundance of different places where they might be used.

But hopefully the conversations we've had recently will help us converge toward a common intuition of how pattern-matching can best be utilized for improved readability.

<br><br>

- resolves https://github.com/flutter/flutter/issues/152313
- Design Doc: [flutter.dev/go/dart-patterns](https://flutter.dev/go/dart-patterns)
This commit is contained in:
Nate Wilson
2024-10-03 12:21:04 -06:00
committed by GitHub
parent 91eb8d226d
commit 5ecf10052f
46 changed files with 378 additions and 671 deletions

View File

@@ -302,14 +302,14 @@ DevFSContent? processSkSLBundle(String? bundlePath, {
throw Exception('SkSL bundle was invalid');
}
final String? parsedPlatform = bundle['platform'] as String?;
TargetPlatform? bundleTargetPlatform;
if (parsedPlatform != null) {
bundleTargetPlatform = getTargetPlatformForName(parsedPlatform);
}
if (bundleTargetPlatform == null || bundleTargetPlatform != targetPlatform) {
final TargetPlatform? bundlePlatform = switch (bundle['platform'] as String?) {
final String platform => getTargetPlatformForName(platform),
null => null,
};
if (bundlePlatform != targetPlatform) {
logger.printError(
'The SkSL bundle was created for $bundleTargetPlatform, but the current '
'The SkSL bundle was created for $bundlePlatform, but the current '
'platform is $targetPlatform. This may lead to less efficient shader '
'caching.'
);

View File

@@ -349,10 +349,8 @@ class DaemonConnection {
} else {
_incomingCommands.add(message);
}
} else if (data['event'] != null) {
// This is an event
_logger.printTrace('<- Event received: ${data['event']}');
final Object? eventName = data['event'];
} else if (data case {'event': final Object eventName}) {
_logger.printTrace('<- Event received: $eventName');
if (eventName is String) {
_events.add(DaemonEventData(
eventName,

View File

@@ -16,31 +16,23 @@ class DartDependencyPackage {
});
factory DartDependencyPackage.fromHashMap(dynamic packageInfo) {
String name = '';
String version = '';
String source = '';
List<dynamic> dependencies = <dynamic>[];
if (packageInfo is LinkedHashMap) {
final LinkedHashMap<String, dynamic> info = packageInfo as LinkedHashMap<String, dynamic>;
if (info.containsKey('name')) {
name = info['name'] as String;
}
if (info.containsKey('version')) {
version = info['version'] as String;
}
if (info.containsKey('source')) {
source = info['source'] as String;
}
if (info.containsKey('dependencies')) {
dependencies = info['dependencies'] as List<dynamic>;
}
if (packageInfo is! LinkedHashMap) {
return DartDependencyPackage(
name: '',
version: '',
source: '',
dependencies: <String>[],
);
}
return DartDependencyPackage(
name: name,
version: version,
source: source,
dependencies: dependencies.map((dynamic e) => e.toString()).toList(),
name: packageInfo['name'] as String? ?? '',
version: packageInfo['version'] as String? ?? '',
source: packageInfo['source'] as String? ?? '',
dependencies: switch (packageInfo['dependencies'] as List<Object?>?) {
final List<Object?> list => list.map((Object? e) => '$e').toList(),
null => <String>[],
},
);
}

View File

@@ -166,11 +166,10 @@ class FlutterManifest {
/// - assets/foo_license.txt
/// ```
List<String> get additionalLicenses {
final Object? licenses = _flutterDescriptor['licenses'];
if (licenses is YamlList) {
return licenses.map((Object? element) => element.toString()).toList();
}
return <String>[];
return <String>[
if (_flutterDescriptor case {'licenses': final YamlList list})
for (final Object? item in list) '$item',
];
}
/// True if this manifest declares a Flutter module project.
@@ -197,27 +196,19 @@ class FlutterManifest {
/// such declaration.
String? get androidPackage {
if (isModule) {
final Object? module = _flutterDescriptor['module'];
if (module is YamlMap) {
return module['androidPackage'] as String?;
if (_flutterDescriptor case {'module': final YamlMap map}) {
return map['androidPackage'] as String?;
}
}
final Map<String, Object?>? platforms = supportedPlatforms;
if (platforms == null) {
late final YamlMap? plugin = _flutterDescriptor['plugin'] as YamlMap?;
return switch (supportedPlatforms) {
{'android': final YamlMap map} => map['package'] as String?,
// Pre-multi-platform plugin format
if (isPlugin) {
final YamlMap? plugin = _flutterDescriptor['plugin'] as YamlMap?;
return plugin?['androidPackage'] as String?;
}
return null;
}
if (platforms.containsKey('android')) {
final Object? android = platforms['android'];
if (android is YamlMap) {
return android['package'] as String?;
}
}
return null;
null when isPlugin => plugin?['androidPackage'] as String?,
_ => null,
};
}
/// Returns the deferred components configuration if declared. Returns
@@ -253,9 +244,8 @@ class FlutterManifest {
/// module descriptor. Returns null if there is no such declaration.
String? get iosBundleIdentifier {
if (isModule) {
final Object? module = _flutterDescriptor['module'];
if (module is YamlMap) {
return module['iosBundleIdentifier'] as String?;
if (_flutterDescriptor case {'module': final YamlMap map}) {
return map['iosBundleIdentifier'] as String?;
}
}
return null;

View File

@@ -396,15 +396,14 @@ class IOSCoreDevice {
required Logger logger,
}) {
final List<_IOSCoreDeviceCapability> capabilitiesList = <_IOSCoreDeviceCapability>[
if (data['capabilities'] case final List<Object?> capabilitiesData)
if (data case {'capabilities': final List<Object?> capabilitiesData})
for (final Object? capabilityData in capabilitiesData)
if (capabilityData != null && capabilityData is Map<String, Object?>)
_IOSCoreDeviceCapability.fromBetaJson(capabilityData),
];
_IOSCoreDeviceConnectionProperties? connectionProperties;
if (data['connectionProperties'] is Map<String, Object?>) {
final Map<String, Object?> connectionPropertiesData = data['connectionProperties']! as Map<String, Object?>;
if (data case {'connectionProperties': final Map<String, Object?> connectionPropertiesData}) {
connectionProperties = _IOSCoreDeviceConnectionProperties.fromBetaJson(
connectionPropertiesData,
logger: logger,
@@ -412,14 +411,12 @@ class IOSCoreDevice {
}
IOSCoreDeviceProperties? deviceProperties;
if (data['deviceProperties'] is Map<String, Object?>) {
final Map<String, Object?> devicePropertiesData = data['deviceProperties']! as Map<String, Object?>;
if (data case {'deviceProperties': final Map<String, Object?> devicePropertiesData}) {
deviceProperties = IOSCoreDeviceProperties.fromBetaJson(devicePropertiesData);
}
_IOSCoreDeviceHardwareProperties? hardwareProperties;
if (data['hardwareProperties'] is Map<String, Object?>) {
final Map<String, Object?> hardwarePropertiesData = data['hardwareProperties']! as Map<String, Object?>;
if (data case {'hardwareProperties': final Map<String, Object?> hardwarePropertiesData}) {
hardwareProperties = _IOSCoreDeviceHardwareProperties.fromBetaJson(
hardwarePropertiesData,
logger: logger,
@@ -535,8 +532,7 @@ class _IOSCoreDeviceConnectionProperties {
required Logger logger,
}) {
List<String>? localHostnames;
if (data['localHostnames'] is List<Object?>) {
final List<Object?> values = data['localHostnames']! as List<Object?>;
if (data case {'localHostnames': final List<Object?> values}) {
try {
localHostnames = List<String>.from(values);
} on TypeError {
@@ -545,8 +541,7 @@ class _IOSCoreDeviceConnectionProperties {
}
List<String>? potentialHostnames;
if (data['potentialHostnames'] is List<Object?>) {
final List<Object?> values = data['potentialHostnames']! as List<Object?>;
if (data case {'potentialHostnames': final List<Object?> values}) {
try {
potentialHostnames = List<String>.from(values);
} on TypeError {
@@ -700,12 +695,12 @@ class _IOSCoreDeviceHardwareProperties {
required Logger logger,
}) {
_IOSCoreDeviceCPUType? cpuType;
if (data['cpuType'] case final Map<String, Object?> betaJson) {
if (data case {'cpuType': final Map<String, Object?> betaJson}) {
cpuType = _IOSCoreDeviceCPUType.fromBetaJson(betaJson);
}
List<_IOSCoreDeviceCPUType>? supportedCPUTypes;
if (data['supportedCPUTypes'] case final List<Object?> values) {
if (data case {'supportedCPUTypes': final List<Object?> values}) {
supportedCPUTypes = <_IOSCoreDeviceCPUType>[
for (final Object? cpuTypeData in values)
if (cpuTypeData is Map<String, Object?>)
@@ -714,8 +709,7 @@ class _IOSCoreDeviceHardwareProperties {
}
List<int>? supportedDeviceFamilies;
if (data['supportedDeviceFamilies'] is List<Object?>) {
final List<Object?> values = data['supportedDeviceFamilies']! as List<Object?>;
if (data case {'supportedDeviceFamilies': final List<Object?> values}) {
try {
supportedDeviceFamilies = List<int>.from(values);
} on TypeError {

View File

@@ -468,10 +468,8 @@ class XcodeAutomationScriptResponse {
factory XcodeAutomationScriptResponse.fromJson(Map<String, Object?> data) {
XcodeAutomationScriptDebugResult? debugResult;
if (data['debugResult'] != null && data['debugResult'] is Map<String, Object?>) {
debugResult = XcodeAutomationScriptDebugResult.fromJson(
data['debugResult']! as Map<String, Object?>,
);
if (data case {'debugResult': final Map<String, Object?> resultData}) {
debugResult = XcodeAutomationScriptDebugResult.fromJson(resultData);
}
return XcodeAutomationScriptResponse._(
status: data['status'] is bool? ? data['status'] as bool? : null,

View File

@@ -862,33 +862,26 @@ class ParsedProjectInfo {
final List<String> parsedSwiftPackageProductDependencies = <String>[];
final List<String> parsedLocalSwiftPackageProductDependencies = <String>[];
if (data['objects'] is Map<String, Object?>) {
final Map<String, Object?> values =
data['objects']! as Map<String, Object?>;
if (data case {'objects': final Map<String, Object?> values}) {
for (final String key in values.keys) {
if (values[key] is Map<String, Object?>) {
final Map<String, Object?> details =
values[key]! as Map<String, Object?>;
if (details['isa'] is String) {
final String objectType = details['isa']! as String;
if (objectType == 'PBXBuildFile') {
if (values[key] case final Map<String, Object?> details) {
switch (details['isa']) {
case 'PBXBuildFile':
buildFiles.add(key);
} else if (objectType == 'PBXFileReference') {
case 'PBXFileReference':
references.add(key);
} else if (objectType == 'PBXGroup') {
case 'PBXGroup':
groups.add(ParsedProjectGroup.fromJson(key, details));
} else if (objectType == 'PBXFrameworksBuildPhase') {
buildPhases.add(
ParsedProjectFrameworksBuildPhase.fromJson(key, details));
} else if (objectType == 'PBXNativeTarget') {
case 'PBXFrameworksBuildPhase':
buildPhases.add(ParsedProjectFrameworksBuildPhase.fromJson(key, details));
case 'PBXNativeTarget':
native.add(ParsedNativeTarget.fromJson(key, details));
} else if (objectType == 'PBXProject') {
case 'PBXProject':
project.add(ParsedProject.fromJson(key, details));
} else if (objectType == 'XCSwiftPackageProductDependency') {
case 'XCSwiftPackageProductDependency':
parsedSwiftPackageProductDependencies.add(key);
} else if (objectType == 'XCLocalSwiftPackageReference') {
case 'XCLocalSwiftPackageReference':
parsedLocalSwiftPackageProductDependencies.add(key);
}
}
}
}
@@ -935,27 +928,16 @@ class ParsedProjectInfo {
/// Representation of data parsed from PBXGroup section in Xcode project's project.pbxproj.
class ParsedProjectGroup {
ParsedProjectGroup._(this.identifier, this.children, this.name);
factory ParsedProjectGroup.fromJson(String key, Map<String, Object?> data) {
String? name;
if (data['name'] is String) {
name = data['name']! as String;
} else if (data['path'] is String) {
name = data['path']! as String;
}
final List<String> parsedChildren = <String>[];
if (data['children'] is List<Object?>) {
for (final Object? item in data['children']! as List<Object?>) {
if (item is String) {
parsedChildren.add(item);
}
}
return ParsedProjectGroup._(key, parsedChildren, name);
}
return ParsedProjectGroup._(key, null, name);
}
ParsedProjectGroup.fromJson(this.identifier, Map<String, Object?> data)
: children = switch (data['children']) {
final List<Object?> children => children.whereType<String>().toList(),
_ => null,
},
name = switch (data) {
{'name': final String name} => name,
{'path': final String path} => path,
_ => null,
};
final String identifier;
final List<String>? children;
@@ -965,21 +947,13 @@ class ParsedProjectGroup {
/// Representation of data parsed from PBXFrameworksBuildPhase section in Xcode
/// project's project.pbxproj.
class ParsedProjectFrameworksBuildPhase {
ParsedProjectFrameworksBuildPhase._(this.identifier, this.files);
factory ParsedProjectFrameworksBuildPhase.fromJson(
String key, Map<String, Object?> data) {
final List<String> parsedFiles = <String>[];
if (data['files'] is List<Object?>) {
for (final Object? item in data['files']! as List<Object?>) {
if (item is String) {
parsedFiles.add(item);
}
}
return ParsedProjectFrameworksBuildPhase._(key, parsedFiles);
}
return ParsedProjectFrameworksBuildPhase._(key, null);
}
ParsedProjectFrameworksBuildPhase.fromJson(
this.identifier,
Map<String, Object?> data,
) : files = switch (data['files']) {
final List<Object?> files => files.whereType<String>().toList(),
_ => null,
};
final String identifier;
final List<String>? files;
@@ -988,31 +962,15 @@ class ParsedProjectFrameworksBuildPhase {
/// Representation of data parsed from PBXNativeTarget section in Xcode project's
/// project.pbxproj.
class ParsedNativeTarget {
ParsedNativeTarget._(
this.data,
this.identifier,
this.name,
this.packageProductDependencies,
);
factory ParsedNativeTarget.fromJson(String key, Map<String, Object?> data) {
String? name;
if (data['name'] is String) {
name = data['name']! as String;
}
final List<String> parsedChildren = <String>[];
if (data['packageProductDependencies'] is List<Object?>) {
for (final Object? item
in data['packageProductDependencies']! as List<Object?>) {
if (item is String) {
parsedChildren.add(item);
}
}
return ParsedNativeTarget._(data, key, name, parsedChildren);
}
return ParsedNativeTarget._(data, key, name, null);
}
ParsedNativeTarget.fromJson(this.identifier, this.data)
: name = switch (data) {
{'name': final String name} => name,
_ => null,
},
packageProductDependencies = switch (data['packageProductDependencies']) {
final List<Object?> dependencies => dependencies.whereType<String>().toList(),
_ => null,
};
final Map<String, Object?> data;
final String identifier;
@@ -1023,24 +981,11 @@ class ParsedNativeTarget {
/// Representation of data parsed from PBXProject section in Xcode project's
/// project.pbxproj.
class ParsedProject {
ParsedProject._(
this.data,
this.identifier,
this.packageReferences,
);
factory ParsedProject.fromJson(String key, Map<String, Object?> data) {
final List<String> parsedChildren = <String>[];
if (data['packageReferences'] is List<Object?>) {
for (final Object? item in data['packageReferences']! as List<Object?>) {
if (item is String) {
parsedChildren.add(item);
}
}
return ParsedProject._(data, key, parsedChildren);
}
return ParsedProject._(data, key, null);
}
ParsedProject.fromJson(this.identifier, this.data)
: packageReferences = switch (data['packageReferences']) {
final List<Object?> references => references.whereType<String>().toList(),
_ => null,
};
final Map<String, Object?> data;
final String identifier;

View File

@@ -851,8 +851,8 @@ class FlutterVmService {
? <String, Object>{'value': platform}
: <String, String>{},
);
if (result != null && result['value'] is String) {
return result['value']! as String;
if (result case {'value': final String value}) {
return value;
}
return 'unknown';
}

View File

@@ -423,14 +423,11 @@ abstract class FlutterTestDriver {
final StringBuffer error = StringBuffer();
error.write('Received app.stop event while waiting for $interestingOccurrence\n\n$_errorBuffer');
final Object? jsonParams = json['params'];
if (jsonParams is Map<String, Object?>) {
if (jsonParams['error'] != null) {
error.write('${jsonParams['error']}\n\n');
}
final Object? trace = jsonParams['trace'];
if (trace != null) {
error.write('$trace\n\n');
}
if (jsonParams case {'error': final Object errorObject}) {
error.write('$errorObject\n\n');
}
if (jsonParams case {'trace': final Object trace}) {
error.write('$trace\n\n');
}
response.completeError(Exception(error.toString()));
}