rspec/rules/S7054/dart/rule.adoc
github-actions[bot] 1cdcbab02e
Create rule S7054: "is!" should be used instead of "!is"
Co-authored-by: Marharyta Nedzelska <margarita.nedzelska@sonarsource.com>
2024-08-30 15:45:28 +02:00

71 lines
2.0 KiB
Plaintext

== Why is this an issue?
Dart has an `is` operator to check the type of a variable. This operator can also be used with negation `is!`. In this case we check that the type of a variable on the left side of the operator is not the one mentioned io the right side.
Similar operators also exist in other languages, but they might have different spelling. For example, in Kotlin, the same operator is written this way: `!is`. Developers familiar with both languages might confuse these 2 operators. Unfortunately, this won't lead to a compile time error, but will change the semantic of your code.
In Dart, `x is! Y`, will return `true` is `x` is not of type `Y` and will return `false`, if `x` is of type `Y`.
On the other hand `x !is Y` will apply null assertion operator (`!`) to `x` and then return `true` if `x` is of type `Y`, and return `false` if it is not.
=== What is the potential impact?
It's hard to estimate the impact taking into account that, firstly `x!` can throw an exception and then, the resulted check will have an absolutely opposite meaning.
== How to fix it
If the intention was to use `is!`, then replace `!is` with `is!`. If null assertion was used on purpose, then, this should be explicit and there must be a space between `!` and `is`.
=== Code examples
==== Noncompliant code example
[source,dart,diff-id=1,diff-type=noncompliant]
----
void main(dynamic s) {
if (s !is String) { // Noncompliant
print('s is not a String!');
}
}
----
==== Compliant solution
[source,dart,diff-id=1,diff-type=compliant]
----
void main(dynamic s) {
if (s is! String) {
print('s is not a String!');
}
}
----
== Resources
=== Documentation
* Dart Docs - https://dart.dev/language/operators[Operators]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Use "is!" instead of "!is".
=== Highlighting
`!` and `is` operators
'''
== Comments And Links
(visible only on this page)
endif::env-github,rspecator-view[]