Create rule S4275: Getters should access the expected fields (#4734)

* Add rust to rule S4275

* 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:54 +01:00 committed by GitHub
parent dc98004888
commit 982f059788
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,8 @@
{
"title": "Getters should access the expected fields",
"tags": [
"pitfall",
"clippy"
],
"quickfix": "unknown"
}

View File

@ -0,0 +1,56 @@
== Why is this an issue?
Getters provide a way to enforce encapsulation by providing methods that give controlled access to struct fields. However, in structs with multiple fields, it is not unusual that copy and paste is used to quickly create the needed getters, which can result in the wrong field being accessed by a getter.
== How to fix it
To fix the issue of incorrect field access in getters, ensure that each getter method correctly accesses the intended field.
=== Code examples
==== Noncompliant code example
[source,rust,diff-id=1,diff-type=noncompliant]
----
struct MyStruct {
field1: i32,
field2: i32,
}
impl MyStruct {
// Incorrectly accessing field2 instead of field1
fn get_field1(&self) -> i32 {
self.field2
}
fn get_field2(&self) -> i32 {
self.field2
}
}
----
==== Compliant solution
[source,rust,diff-id=1,diff-type=compliant]
----
struct MyStruct {
field1: i32,
field2: i32,
}
impl MyStruct {
// Correctly accessing field1
fn get_field1(&self) -> i32 {
self.field1
}
fn get_field2(&self) -> i32 {
self.field2
}
}
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#misnamed_getters