rspec/rules/S1165/java/rule.adoc

77 lines
1.7 KiB
Plaintext

== Why is this an issue?
When a class has all `final` fields, the compiler ensures that the object's state remains constant. It also enforces a clear design intent of
immutability, making the class easier to reason about and use correctly.
Exceptions are meant to represent the application's state at the point at which an error occurred.
Making all fields in an `Exception` class `final` ensures that these class fields do not change after initialization.
=== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
public class MyException extends Exception {
private int status; // Noncompliant
public MyException(String message) {
super(message);
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
----
=== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public class MyException extends Exception {
private final int status; // Compliant
public MyException(String message, int status) {
super(message);
this.status = status;
}
public int getStatus() {
return status;
}
}
----
== Resources
* Effective Java 3rd Edition, Joshua Bloch - Exceptions - Item 76 : Strive for failure atomicity
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Make this field "xxxx" final.
'''
== Comments And Links
(visible only on this page)
=== on 30 Jul 2013, 16:55:45 Freddy Mallet wrote:
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-254
=== on 14 Mar 2017, 11:40:35 Amaury Levé wrote:
\[~valeri.hristov] This seems to be a nice rule to implement for C#. WDYT?
endif::env-github,rspecator-view[]