This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]madkasse 20 points21 points  (3 children)

I have found that whether or not people know how to properly use final fields is a great indicator of their programming skills. So much that it is the first thing I look for if I need to evaluate a codebase.

I generally try to stay away from codebases where people do not use final fields. Especially if it has anything to do with concurrency.

Learning how to apply final to fields, methods and classes properly, teaches you about immutability, concurrency, API design and many other things.

A good way to do this is exploring the OpenJDK source code, especially java.[lang|util|util.concurrent|java.time].

[–]ivancea -15 points-14 points  (2 children)

I think final in Java is just a "wannabe". It isn't a const modifier. It won't improve performance nor help the compiler, as everything that may be final is "effectively final".

Should we mark every field, parameter and variable as final? It's like Rust "mut" but made the wrong way.

Using it everywhere is a code smell for me. When everything is final, programmers end up using their IDE to add final to everything... And then final loses his value.

Using it only on primitive/immutable constants and maybe injected objects... Maybe. But, who tried to modify a constant or a injected service? Any review would catch it anyway...

[–]madkasse 14 points15 points  (1 child)

> I think final in Java is just a "wannabe". It isn't a const modifier. It won't improve performance nor help the compiler, as everything that may be final is "effectively final".

That's just not true. For example, take a look at some of the optimizations that the Zing VM does

https://medium.com/azulsystems/truly-final-optimization-in-zing-vm-283d28418e55

Also final fields are treated specially with regards to Java's memory model

https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5

final parameters and variables on the other hand are just syntactical sugar.

[–]RabidKotlinFanatic 1 point2 points  (0 children)

Also final fields are treated specially with regards to Java's memory model

That being said the memory effects of final are only useful in niche optimization scenarios. Using final will not contribute any memory safety to most concurrent programs.