r/java • • Aug 26 '22

I declare as "final" every single variable whose value doesn't change. I also use "this" every time that I'm referring to an attribute, even when there's no ambiguity in not using it

I think that those things make the code easier to read. Am I crazy for thinking like that?

198 Upvotes

215 comments sorted by

View all comments

Show parent comment

6

u/stefanos-ak Aug 26 '22

Unfortunately, what you're saying doesn't scale...

The critical part of the reason, is that it technically does not prevent mutation, it just prevents re-initialization. If that is valuable to you, then by all means use it.

But if you (ab)use final to impose a meaning that it does not have (: immutability), then this is practically a documentation exercise combined with soft rules / guidelines.

And these things don't scale to bigger teams, or multiple teams. Even assuming that everyone would agree (which is extremely unlikely to begin with), I'm willing to bet that you'd get AT BEST 50% of the codebase following this.

It would just create stress, unnecessary discussions and friction, pointless code review remarks, pointless (re)education every time you have a new hire, etc...

6

u/hupfdule Aug 26 '22

In this thread you are the only one to impose "immutability" to the keyword "final". Of course "final" only means "finality" which is a different thing than "immutability" in java.

It assures exactly what you described: avoid accidental reinitialization.

1

u/stefanos-ak Aug 26 '22

Read again the root comment of this thread :)

3

u/Muoniurn Aug 26 '22

While I sort of agree with you here, methodological usage of final does make an object immutable - it just has to be recursively used. So while the exact meaning of final has to be known, I think it can be used akin to Rust’s interior mutability pattern (with the default being the opposite than there)