r/javahelp • u/3AMgeek • Apr 05 '24
Using final with every variable.
Hi, Does it really makes sense to use final keyword with every field, and even setters and constructors parameters?
21
Upvotes
r/javahelp • u/3AMgeek • Apr 05 '24
Hi, Does it really makes sense to use final keyword with every field, and even setters and constructors parameters?
10
u/MmmmmmJava Apr 05 '24
Variable reassignment is a major root cause to race condition bugs. All mutable state is dangerous.
Other languages solve for this by implicitly making variables final, thereby requiring developers to clearly indicate intention to reassign with the
mutkeyword (mutable).I’ve been on teams that uplifted buggy services by requiring all fields, parameters, and local variables as final and over-night the number of concurrency bugs (caused by reassignment) dropped to zero.
It’s definitely appears noisy in the code if you’re not used to it at first, but once you retrain your brain, seeing a variable without
finaleffectively indicates that the intention is to reassign.In my experience, committing as a team and adding automated checkstyle rules helps prevent missing final keywords and results in far fewer bugs with less complicated code!
Immutability rocks!!!