The Final Straw
While I’m not quite going to blame Java’s final
for the following, I’ve said before how final
should have its place, and that it’s often just noise in other code.
In a recent performance improvement, I experienced an obvious, but hidden side-effect of attacking the inputs to a function. The code was something like this:
1 2 3 4 | @Cacheable public Definition getDefinition(Definition outlineOfDefinition) { ... } |
The calling code wanted to get the full definition from the server, so provides a stub object with the ID in, and gets the populated object back. Note: this is marked as Cacheable
so that subsequent calls will be pulled from the cache, rather than the server.
Unfortunately, what the method did internally involved hacking the input object. This made whatever caching the cache layer was doing not work. Most likely the cache cached the modified object as the request, which subsequent requests didn’t match.
What we need here is NOT to modify inputs to cached methods. It’s obvious, but easily not noticed.
Here’s The Kicker
The code from which the above was taken made extrvagant use of final
everywhere. It was final
this and final
that. Hell, even the parameter that got hacked by the code, breaking caching, may have been marked as final
. What this created was a horrific false sense of security about the quality of the code, and the management of values.
With final
everywhere, it’s hard to see things that aren’t final
because you’re snow blind to it. I think this is the opposite of const
vs let
in JavaScript, where you can see differences, rather than presence/absence.
On top of that, believing an object to be final
is a bit of self-deception. A final
reference may have setters on it, and thus be mutable… and thus cause the problem we encountered here.
TL;DR
- Don’t rewrite input parameters…
- …especially when caching
- Have short methods in place of long-lived immutable references spanning large blocks of code for security
- Use
final
to achieve something special, not as code-seasoning
Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: The Final Straw Opinions expressed by Java Code Geeks contributors are their own. |
Java needs the const modifier just like what c++ has.
About as much as it needs to go back to using
malloc
andfree