60 lines
1.5 KiB
Plaintext
60 lines
1.5 KiB
Plaintext
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
|
|
|
|
----
|
|
public class Foo
|
|
{
|
|
public int instanceData = 32; // Noncompliant
|
|
}
|
|
----
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
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)
|
|
|
|
include::message.adoc[]
|
|
|
|
include::highlighting.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|