rspec/rules/S1104/csharp/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

70 lines
1.6 KiB
Plaintext

== Why is this an issue?
Public fields in public classes do not respect the encapsulation principle and has three main disadvantages:
* Additional behavior such as validation cannot be added.
* The internal representation is exposed, and cannot be changed afterwards.
* Member values are subject to change from anywhere in the code and may not meet the programmer's assumptions.
By using private fields and public properties (set and get), unauthorized modifications are prevented. Properties also benefit from additional protection (security) features such as Link Demands.
Note that due to optimizations on simple properties, public fields provide only very little performance gain.
=== Noncompliant code example
[source,csharp]
----
public class Foo
{
public int instanceData = 32; // Noncompliant
}
----
=== Compliant solution
[source,csharp]
----
public class Foo
{
private int instanceData = 32;
public int InstanceData
{
get { return instanceData; }
set { instanceData = value ; }
}
}
----
=== Exceptions
Fields marked as ``++readonly++`` or ``++const++`` are ignored by this rule.
Fields inside classes or structs annotated with the ``++StructLayoutAttribute++`` are ignored by this rule.
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Make this field 'private' and encapsulate it in a 'public' property.
=== Highlighting
Field identifier.
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]