rspec/rules/S1488/rust/rule.adoc
github-actions[bot] 77af1ab66a
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>
2025-03-19 13:38:03 +00:00

35 lines
1.3 KiB
Plaintext

== 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