Create rule S1488: Local variables should not be declared and then immediately returned (#4732)

* Add rust to rule S1488

* 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 13:38:03 +00:00 committed by GitHub
parent 6cf7f45131
commit 77af1ab66a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 41 additions and 0 deletions

View File

@ -0,0 +1,7 @@
{
"title": "Local variables should not be declared and then immediately returned",
"tags": [
"clumsy",
"clippy"
]
}

View File

@ -0,0 +1,34 @@
== Why is this an issue?
Declaring a variable only to immediately return it is considered a bad practice because it adds unnecessary complexity to the code. This practice can make the code harder to read and understand, as it introduces an extra step that doesn't add any value. Instead of declaring a variable and then immediately returning, it is generally better to return or throw the value directly. This makes the code cleaner, simpler, and easier to understand.
== How to fix it
Declaring a variable only to immediately return it is considered a bad practice because it adds unnecessary complexity to the code. To fix the issue, return the value directly.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
fn compute_duration_in_milliseconds(hours: u32, minutes: u32, seconds: u32) -> u32 {
let duration = (((hours * 60) + minutes) * 60 + seconds) * 1000;
duration
}
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
fn compute_duration_in_milliseconds(hours: u32, minutes: u32, seconds: u32) -> u32 {
(((hours * 60) + minutes) * 60 + seconds) * 1000
}
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#let_and_return