rspec/rules/S7045/dart/rule.adoc

106 lines
2.6 KiB
Plaintext

In Dart, local variables don't have a concept of "private visibility" and should not start with an underscore.
== Why is this an issue?
The underscore prefix is used in Dart to indicate members and top-level declarations that are private.
The compiler enforces access restrictions so that private elements can only be accessed from within the library in which they are declared.
Because local variables and parameters are only accessible within the scope in which they are declared, and cannot be exposed to other libraries, the private accessibility scope doesn't apply to them. Using an underscore prefix for local variables suggests otherwise and can be misleading.
This rule applies to local variables and parameters of:
* top-level functions
* nested functions and lambdas
* class methods
* class constructors
* extension and extension type methods
=== Exceptions
Unused parameters are typically named ``++__++``, ``++___++``, etc. to indicate that they are intentionally unused. This is a common practice and is not considered a violation of this rule.
Typical examples of this practice arise with lambdas:
[source,dart]
----
List<int> repeat(int value, int times) =>
List<int>.generate(times, (_) => value); // OK
----
as well as in pattern matches with https://dart.dev/language/pattern-types#wildcard[wildcards]:
[source,dart]
----
String rating(double probability) => switch (probability) {
< 1.05 => 'A',
< 20.0 => 'B',
< 50.0 => 'C',
_ => 'D', // OK
};
----
as well as catch clauses:
[source,dart]
----
try {
// ...
} on Exception catch (_, s) { // OK
print(s);
}
----
== How to fix it
=== Code examples
==== Noncompliant code example
[source,dart,diff-id=1,diff-type=noncompliant]
----
void doSomething(int myParam) {
int LOCAL; // Noncompliant
// ...
}
----
==== Compliant solution
[source,dart,diff-id=1,diff-type=compliant]
----
void doSomething(int myParam) {
int local; // Noncompliant
// ...
}
----
== Resources
=== Documentation
* Dart Docs - https://dart.dev/tools/linter-rules/no_leading_underscores_for_local_identifiers[Dart Linter rule - no_leading_underscores_for_local_identifiers]
* Dart Docs - https://dart.dev/language/libraries[Language - Syntax basics - Libraries & imports]
* Dart Docs - https://dart.dev/language/pattern-types#wildcard[Language - Pattern types - Wildcard]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* The local variable '<identifier_name>' starts with an underscore.
=== Highlighting
* The identifier.
'''
== Comments And Links
(visible only on this page)
endif::env-github,rspecator-view[]