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:
parent
dc98004888
commit
982f059788
8
rules/S4275/rust/metadata.json
Normal file
8
rules/S4275/rust/metadata.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"title": "Getters should access the expected fields",
|
||||
"tags": [
|
||||
"pitfall",
|
||||
"clippy"
|
||||
],
|
||||
"quickfix": "unknown"
|
||||
}
|
56
rules/S4275/rust/rule.adoc
Normal file
56
rules/S4275/rust/rule.adoc
Normal 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
|
Loading…
x
Reference in New Issue
Block a user