I have not been using the final
Java keyword when I was an inexperienced software developer. This was a mysterious keyword to me for a long time. Especially for local variables inside a method, I asked myself: why would immutable values make sense? There are opinions on the web proving that I am not the only one asking this question.
In this article I will present some code snippets that may shed a little light on immutability. It is not easy to understand why we should use final
as much as possible. The realization comes only over time when you have seen a lot of the buggy code that is around everywhere. Long methods are the home of mutability mistakes.
The Java source code below implements the following story:
Seems to be an application for travellers ...
1 | private boolean shouldGoWalking( |
It is easy to see that this code doesn't work as expected. The problem starts at line 12. When a park is in reach, the weather simply is ignored. S... happens.
How can we detect such bugs quickly? You got it: make everything final (even the parameters). I wouldn't even try to understand the code before doing this.
7 | final boolean goWalking; |
Consequence is that you can assign a value just once. The compiler will show you immediately all places where the variable is assigned, and there you have the bug.
1 | private boolean shouldGoWalking( |
I made two steps in one:
acceptableWeather
and parkInReach
final
access modifierThis is also much better readable code.
Most mutability bugs I've seen happened with String
and boolean
variables.
Actually it is quite easy to realize the value of immutability:
If you sum this up, you find out that you should use as much immutable class fields, parameters and local values as possible. The final
keyword does not cutter code. It proves that you were thinking while programming.
ɔ⃝ Fritz Ritzberger, 2021-02-13