rspec/rules/S4275/vbnet/rule.adoc

89 lines
2.4 KiB
Plaintext
Raw Permalink Normal View History

== Why is this an issue?
Properties provide a way to enforce https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)[encapsulation] by providing property procedures that give controlled access to `Private` fields. However, in classes with multiple fields, it is not unusual that https://en.wikipedia.org/wiki/Copy-and-paste_programming[copy-and-paste] is used to quickly create the needed properties, which can result in the wrong field being accessed by the property procedures.
2020-06-30 12:49:37 +02:00
[source,vbnet]
----
Class C
Private _x As Integer
Private _Y As Integer
2021-02-02 15:02:10 +01:00
Public ReadOnly Property Y As Integer
Get
Return _x ' Noncompliant: The returned field should be '_y'
End Get
End Property
End Class
----
This rule raises an issue in any of these cases:
2020-06-30 12:49:37 +02:00
* A get procedure does not access the field with the corresponding name.
* A set procedure does not update the field with the corresponding name.
2020-06-30 12:49:37 +02:00
For simple properties, it is better to use https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/auto-implemented-properties[auto-implemented properties] (VB.NET 10.0 or later).
2021-02-02 15:02:10 +01:00
2020-06-30 12:49:37 +02:00
Field and property names are compared as case-insensitive. All underscore characters are ignored.
== How to fix it
2020-06-30 12:49:37 +02:00
=== Code examples
==== Noncompliant code example
[source,vbnet,diff-id=1,diff-type=noncompliant]
2020-06-30 12:49:37 +02:00
----
Public Class Sample
2020-06-30 12:49:37 +02:00
Private _x As Integer
Private _y As Integer
2020-06-30 12:49:37 +02:00
Public Property Y As Integer
Get
Return _x ' Noncompliant: field '_y' is not used in the return value
2020-06-30 12:49:37 +02:00
End Get
Set(value As Integer)
_x = value ' Noncompliant: field '_y' is not updated
2020-06-30 12:49:37 +02:00
End Set
End Property
2020-06-30 12:49:37 +02:00
End Class
----
==== Compliant solution
2020-06-30 12:49:37 +02:00
[source,vbnet,diff-id=1,diff-type=compliant]
2020-06-30 12:49:37 +02:00
----
Public Class Sample
2020-06-30 12:49:37 +02:00
Private _x As Integer
Private _y As Integer
2020-06-30 12:49:37 +02:00
Public Property Y As Integer
Get
Return _y
2020-06-30 12:49:37 +02:00
End Get
Set(value As Integer)
_y = value
2020-06-30 12:49:37 +02:00
End Set
End Property
2020-06-30 12:49:37 +02:00
End Class
----
== Resources
* Microsoft Learn: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/property-procedures[Property Procedures (Visual Basic)]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
include::../highlighting.adoc[]
endif::env-github,rspecator-view[]