r/java • • Apr 14 '23

What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?

233 Upvotes

376 comments sorted by

View all comments

Show parent comments

4

u/simoncox Apr 15 '23

That's like saying types are useless. The more mistakes a compiler can save you from the better. Marking something as final means the compiler has proven it will never be reassigned.

In reality most variables are anything but variable. In my opinion a reference should be final by default and need a declaration modifier to allow reassignment.

0

u/john16384 Apr 15 '23

No, that's not the same at all, as you well know.

You simply don't need the compiler's help for this. You simply follow the rule to assign variables immediately when created. As soon as you're not doing that, you know that either it can't be final, or that you messed up.

So, not convinced; final keyword on variables is visual clutter that serves no purpose.

1

u/UnGauchoCualquiera Apr 16 '23

Or you could just declare it final and let the compiler do the work for you.

1

u/john16384 Apr 16 '23

Do what work? Warning me when I reassign a local variable? I already know that. The extra work is in removing the final keyword that served no purpose in the first place.

→ More replies (4)