By checking all the fields in the final class, you make it clear that you intend your class to be immutable.
Suppose you have the following class:
public class Immutable { private int value; public Immutable (int value) { this.value = value; } public int getValue () { return value; } }
There is no setter method, so you can easily assume that this class is immutable. What is it, at the moment. But in the end, your class will be modified by another programmer, and this programmer can add some methods to your class:
public class Immutable { private int value; public Immutable (int value) { this.value = value; } public int getValue () { return value; } public void doSomething () { value++; } }
It is very easy to inadvertently add a method that changes the state of your object if the fields are not final . By marking them final , this other programmer will receive a compilation error when he tries to change the field, and will have to ask himself why this field is final , and modifying it violates the contract of this class.
It can be argued that Javadoc should be used to document that the specified class is immutable, but frankly, not everyone reads Javadoc. In my opinion, making code is better for yourself.
source share