rspec/rules/S3562/dart/rule.adoc
Marharyta c3aa4b07c5
Add more Dart rules (#4062)
* Modify rule S6582: Add Dart language

* Modify rule S6606: Add Dart language

* Modify rule S6207: Add Dart language

* Modify rule S1116: Add Dart example with empty "else"

* Modify rule S927: Add Dart language

* Modify rule S1155: Add Dart language

* Modify rule S2933: Add Dart language

* Modify rule S2971: Add Dart language

* Modify rule S4123: Add Dart language

* Modify rule S120: Add Dart language

* Modify rule S1679: Add Dart language

* Modify rule S2159: Add Dart language

* Modify rule S3257: Add Dart language

* Modify rule S6619: Add Dart language

* Modify rule S3562: Add Dart language

* Modify rule S3240: Add Dart language

* Modify rule S5416: Add Dart language

* Modify rule S2175: Add Dart language

* Modify rule S3962: Add Dart language

* Modify rule S2471: Add Dart language

* Modify rule S3512: Add Dart language

* Modify rule S2432: Add Dart language
2024-07-18 13:20:47 +02:00

95 lines
2.1 KiB
Plaintext

== Why is this an issue?
For completeness, a ``++switch++`` over the values of an ``++enum++`` must either address each value in the ``++enum++`` or contain a ``++default++`` case. ``++switch++`` statements that are not over ``++enum++`` must end with a ``++default++`` case. This exhaustiveness is enforced by compiler. However, in the code there might be other enum-like classes which are not enums according to compiler, but sthe switch over its constants was intended to be exhaustive.
This rule with raise an issue when switch over such enum-like classes doesn't cover all cases.
Enum-like classes are classes that:
* are defined as non-abstract;
* have only one private non-factory constructor
* have two or more static const fields whose type is the enclosing class and
no subclasses of the class is in the defining library
=== Noncompliant code example
[source,dart]
----
class MyEnum {
final int i;
const EnumLike._(this.i);
static const a = MyEnum._(1);
static const b = MyEnum._(2);
static const c = MyEnum._(3);
}
void foo(MyEnum e) {
switch(e) { // Noncompliant, case 'b' is missing
case MyEnum.a:
print('a');
case MyEnum.b:
print('b');
}
}
----
=== Compliant solution
[source,dart]
----
class MyEnum {
final int i;
const EnumLike._(this.i);
static const a = MyEnum._(1);
static const b = MyEnum._(2);
static const c = MyEnum._(3);
}
void foo(MyEnum e) {
switch(e) {
case MyEnum.a:
print('a');
case MyEnum.b:
print('b');
case MyEnum.c:
print('c');
}
}
----
or
[source,dart]
----
class MyEnum {
final int i;
const EnumLike._(this.i);
static const a = MyEnum._(1);
static const b = MyEnum._(2);
static const c = MyEnum._(3);
}
void foo(MyEnum e) {
switch(e) {
case MyEnum.a:
print('a');
break;
case MyEnum.b:
print('b');
break;
default:
print('default');
}
}
----
== Resources
* https://dart.dev/tools/linter-rules/exhaustive_cases[Dart Lint rule]
* https://dart.dev/language/branches#exhaustiveness-checking[Exhaustiveness checking]