From 982f0597889a63393d69b6a89fbfbdc6f5ca5f33 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 19 Mar 2025 14:37:54 +0100 Subject: [PATCH] Create rule S4275: Getters should access the expected fields (#4734) * Add rust to rule S4275 * Update RSPEC --------- Co-authored-by: yassin-kammoun-sonarsource Co-authored-by: yassin-kammoun-sonarsource --- rules/S4275/rust/metadata.json | 8 +++++ rules/S4275/rust/rule.adoc | 56 ++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 rules/S4275/rust/metadata.json create mode 100644 rules/S4275/rust/rule.adoc diff --git a/rules/S4275/rust/metadata.json b/rules/S4275/rust/metadata.json new file mode 100644 index 0000000000..336885c72a --- /dev/null +++ b/rules/S4275/rust/metadata.json @@ -0,0 +1,8 @@ +{ + "title": "Getters should access the expected fields", + "tags": [ + "pitfall", + "clippy" + ], + "quickfix": "unknown" +} diff --git a/rules/S4275/rust/rule.adoc b/rules/S4275/rust/rule.adoc new file mode 100644 index 0000000000..88dae64349 --- /dev/null +++ b/rules/S4275/rust/rule.adoc @@ -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