Create rule S7411: Shared code in all branches should be extracted (#4744)

* Create rule S7411

* Update RSPEC

---------

Co-authored-by: yassin-kammoun-sonarsource <yassin-kammoun-sonarsource@users.noreply.github.com>
Co-authored-by: yassin-kammoun-sonarsource <yassin.kammoun@sonarsource.com>
This commit is contained in:
github-actions[bot] 2025-03-19 14:37:27 +01:00 committed by GitHub
parent 91eadda5cf
commit 06526591dd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1,2 @@
{
}

View File

@ -0,0 +1,24 @@
{
"title": "Shared code in all branches should be extracted",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"clippy"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-7411",
"sqKey": "S7411",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"MAINTAINABILITY": "HIGH"
},
"attribute": "DISTINCT"
}
}

View File

@ -0,0 +1,39 @@
== Why is this an issue?
Having shared code in all branches of an if-statement leads to redundancy, making the code harder to maintain and increasing the risk of errors. It also reduces readability by cluttering the distinct logic of each branch. Extracting shared code into a single location improves maintainability.
== How to fix it
To fix this issue, move the shared code outside of the if-statement branches so that it is executed regardless of the condition.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
let result = if condition {
println!("Hello World");
42
} else {
println!("Hello World");
24
};
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
println!("Hello World");
let result = if condition {
42
} else {
24
};
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#branches_sharing_code