rspec/rules/S1165/java/rule.adoc

77 lines
1.7 KiB
Plaintext
Raw Permalink Normal View History

== 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.
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
[source,java,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
public class MyException extends Exception {
private int status; // Noncompliant
2021-04-28 16:49:39 +02:00
public MyException(String message) {
super(message);
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
[source,java,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
public class MyException extends Exception {
private final int status; // Compliant
2021-04-28 16:49:39 +02:00
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[]