== Why is this an issue?

include::../description.adoc[]

include::../impacts.adoc[]


=== Exceptions

This rule ignores `public final` fields because they are not modifiable. Also, annotated fields, whatever the annotation(s) will be ignored, as annotations are often used by injection frameworks, which in exchange require having public fields.

== How to fix it

Depending on your need there are multiple options:

* Encapsulate the field
    . Make the field private.
    . Define methods to get and set the value of the field. +
    These methods are commonly known as getter and setter methods and are prefixed by `get` and `set` followed by the name of the field. __Note:__ as a bonus it is now possible to monitor value changes using breakpoints.
* Mark the field as `public final` if it is not supposed to change.

=== Code examples

==== Noncompliant code example

[source,java,diff-id=1,diff-type=noncompliant]
----
public class MyClass {

  public static final int SOME_CONSTANT = 0;     // Compliant - constants are not checked

  public String firstName;                       // Noncompliant

}
----

==== Compliant solution

[source,java,diff-id=1,diff-type=compliant]
----
public class MyClass {

  public static final int SOME_CONSTANT = 0;     // Compliant - constants are not checked

  private String firstName;

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

}
----

=== How does this work?

By having a setter and a getter the code can control how the field is accessed and modified. 
For example, adding validation in the setter method will ensure that only valid values are set.

The access modifiers on the setter can also be changed to `private` or `protected` to restrain which code can modify the value.

include::../see.adoc[]

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

include::../message.adoc[]

'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]

endif::env-github,rspecator-view[]
