72 lines
1.8 KiB
Plaintext
72 lines
1.8 KiB
Plaintext
Functions and methods with `void` return type should not return `null`.
|
|
|
|
== Why is this an issue?
|
|
|
|
Dart allows to `return null;` from a function or a method with `void` return type. That happens because, from a technical standpoint, unlike other languages like Java, every function in Dart returns a value: if you don't return a value, `null` will be returned.
|
|
|
|
From a semantical standpoint, however, this can be misleading, as it may suggest that the function does return an intended value, which is not the case.
|
|
|
|
It is better to consistently use `return;` and make it clear that in fact the function does not return any intended value.
|
|
|
|
== How to fix it
|
|
|
|
Replace `return null;` with `return;`.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,dart,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
void logIf(bool condition, String message) {
|
|
if (!condition) {
|
|
return null; // Noncompliant
|
|
}
|
|
|
|
print(message);
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,dart,diff-id=1,diff-type=compliant]
|
|
----
|
|
void logIf(bool condition, String message) {
|
|
if (!condition) {
|
|
return;
|
|
}
|
|
|
|
print(message);
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* Dart Docs - https://dart.dev/tools/linter-rules/avoid_returning_null_for_void[Dart Linter rule - avoid_returning_null_for_void]
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
* Don't return 'null' from a function with a return type of 'void'.
|
|
* Don't return 'null' from a method with a return type of 'void'.
|
|
|
|
=== Highlighting
|
|
|
|
* In the case of a function or method with body: the `return null;` expression, including `;`.
|
|
* In the case of an arrow function or an arrow method: the `=> null;` expression, including `;`.
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
endif::env-github,rspecator-view[]
|