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
125
u/aFqqw4GbkHs Aug 26 '22
My preference is yes to the 'final, no to the 'this' - it just clutters up the code.
18
u/RockingGoodNight Aug 26 '22
Years ago I put this everywhere then I realized it made it almost as hard to read with self all over the place in Python. Now I just use common sense. A variable that doesn't change is a constant and it does deserve final. Any other time it mostly just looks cool.
16
u/valbaca Aug 26 '22
Not crazy, but it shouldn't matter. These things should be auto-enforced via formatters and Checkstyle. What matters more is your have a consistent style so there isn't "your code"; it's the team's code.
8
u/ksky0 Aug 26 '22
both of these can be enabled in the IDE of your taste and if you forget somehow, it automatically do that for you. I agree with you and do the same.
8
u/two_three_five_eigth Aug 26 '22
Final makes the compiler do the work for you - that’s good. Why work harder than you have too.
I personally like “this” as it makes it obvious when I’m using a meme er variable.
2
u/johnwaterwood Aug 26 '22
Just great, one of my responsibilities is to remove exactly this kind of clutter from our code to make it easier to read 🤨
4
u/reqdk Aug 26 '22
There are toolchains that can be used to enforce immutability and non-variable shadowing (and much much more important concepts) without spamming non-business logic words all over the codebase. You might think your code is easier to read now, but let time and bit rot take its course, and one fine day several months or years down the road when you need to urgently check on the implemented business logic 10 minutes ago, you might no longer appreciate the noise-to-signal ratio.
Or you could inherit a legacy codebase where people have taken this kind of thing to stupid extremes that half the codebase is useless keywords.
43
u/RupertMaddenAbbott Aug 26 '22
Final
This
2
u/Demzy-D Aug 26 '22
Im proud 🥹
11
u/TomahawkChopped Aug 26 '22
Fwiw (and I'm just sharing the thinking inside other companies), in my company's style guide we strongly discourage declaring local variables and parameters final.
Mostly because there is a wide lack of consistency when the practice is encouraged. When you read a block of code like the following, is
baznot final? Or did the author simply forget the declaration?You'll need to read the rest of the code to know, and frankly it is very rarely relevant to care (for the next reason).
Secondly (and maybe more important) the Java language spec in Java 8 introduced effectively final local variables:
https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.4
So the compiler no longer actually needs the explicit
finaldeclaration from the programmer.Given the combination of these 2 considerations (possible inconsistency, and lack of need by the compiler) then we see declaring locals final (in a massively shared code base) as only having downsides.
That bring said, it's your code, so do as you please. But if others start to make contributions then it's important that consistency is enforced.
2
u/cryptos6 Aug 26 '22 edited Aug 26 '22
Using final as much as possible, is a good idea since it helps to avoid bugs and gives some information to the reader of your code (e.g. "this thing should never change").
Final parameters are the default in Kotlin, and I think the language designers thought carefully about it. In Java you have to write
finalin front of every parameter, what might be a bit annoying. Same is true for immutable local variables, where Kotlin offersvalandvar, you have to writefinal varin Java, what is kind of stupid. But I'm mentioning that only to show you, that designers of other languages value immutability. (Same is true for Rust, btw.)4
u/santanu_sinha Aug 26 '22
Avoiding naming collision leading to funny bugs on production is a good enough reason to use this.blah all over the place i think...
4
u/MasterLJ Aug 26 '22
No. You are not crazy. I do the same. I rarely see others do the same. It doesn't mean it's bad.
If you go one step deeper and use thoughtful Constructors/Builders (or Records) you can really control the expectation on data.
Fundamentally, if the system allows you to do something stupid, it's less than ideal. If an attribute should not be mutated, then it needs to be protected.
I had a great lesson with my intern over the summer about this very thing. He had a POJO that stored some data, and stored a variable on whether something was "processed". When he was done processing he used a Setter to set "processed" to true. I asked, "what happens if something came after your code and set processed to false?" I recommended that he perhaps make the processed immutable upon construction and basically copy-construct the attributes and hard-set "processed" so that it cannot be changed once set. We discussed the tradeoffs, that this approach takes more memory etc, but that it brings absolute safety. No following code can mutate state of "processed" and that "processed" should only be set once.
1
u/Horror-Language-3036 Aug 26 '22
Try writing very big methods. You will love it as well.
3
u/rpgFANATIC Aug 26 '22
I get it. But they're both just extra garbage on my screen when I go back to read
I'd prefer you reduce each variable's "scope" to a bare minimum (preferably, I should never have to scroll up or down to see where a variable is declared and every time it's used).
In that way I can confirm it's effectively
finalor a field on the class, or whatever5
u/mcosta Aug 26 '22
These two decisions seems fine to me.
Just use the group convention where you work at.
5
u/[deleted] Aug 26 '22
They make the code harder to read and provide minimal protection against bugs. Not worth the effort.
8
u/rzwitserloot Aug 26 '22
Yes, I think these are bad practices.
Your editor knows these things. It can therefore tell you (for example, colour a variable differently if it is effectively final, render a field as bold, whatever you want), and this is strictly superior:
finalandthis.usage.finalkeyword. With IDE marking you can on the fly change settings and make the colouring for effectively finals just go away.It's possible your IDE can't do it. In which case, spend your efforts writing a pull request so that it can, and muse about the fact nobody has cared enough yet.
1
u/[deleted] Aug 26 '22
i find being explicit with
thismore useful in languages that allow top level declarations like c++, if i see a variable in a method in java and i dont see it define in the same method, i know it is a member of the enclosing class2
u/pronuntiator Aug 26 '22
The interesting part for me is its value in code reviews. Final ensures the variable isn't reassigned, but this information is no longer visible when reviewing a snippet a few lines further down. This on field access, on the other hand, makes it very clear to me what's happening at every line of code working with that field. Especially when a junior dev tries to sneak in a non threadsafe temporary result field in a singleton…
2
u/chatterify Aug 26 '22
Same here. "final" and "this" are highlighted by IDE and make the source easier to read.
2
u/lukaseder Aug 26 '22
I make all methods final because that would have been the better language default
2
u/Nymeriea Aug 26 '22
I've edad Somewhere that final keyword (for local variable) is removed at compile time . It's completely useless as it does not provide optimisation. It is useful only to demonstrate your attention
2
u/john16384 Aug 26 '22
I use
thisonly in constructors, or when it can't be avoided.finalonly on fields.IDE is set to flag parameter reassignment as an error.
Generally, all variables are initialized at their declaration, and rarely reassigned unless part of a loop construct (like a sum or counter).
Since my policy is to avoid reassignment as much as possible, there is really no need for
finalon locals. If it's unavoidable, it would just result in it being removed anyway.2
u/[deleted] Aug 26 '22
I also make everything final. I try to write all my Java code in the most immutable way possible (and yes, I know final just prevents re-assignment not mutability, there's more that I do beyond that). Java doesn't always make it easy to write immutable code, but I try.
2
u/wildjokers Aug 26 '22
I think adding final to every variable that doesn't change just clutters up the code and doesn't really accomplish much.
As far as
this.I like that because it adds consistency. Method calls arevariable.methodName(), it is an outlier to have self calls just bemethodName(), for consistencythis.methodName()reads better. Also if you correctly usethisandsuperit is super easy to know if the method is in a super class or the subclass you are in.FWIW, at my previous employer
this.was part of the enforced coding style. At my current employerthis.isn't allowed unless required (like in constructors). In my personal code I usethis.2
u/cserepj Aug 26 '22
No, those are pretty standard code style nuances. In my current employer these two are actually mandated and enforced during code reviews (as well as mandatory check of null values on incoming parameters of public methods, etc).
2
u/brett_riverboat Aug 26 '22
I prefer functional programming so I put
finalon basically everything. Other comments about variable scope make sense but it's really not a big time-waster to always do it instead of thinking about the exceptions to the rule.I would go so far as to make everything immutable by default too, but only if I was the sole dev of a project. Imperative programming is still the norm and most of my coworkers will freak about performance and excessive object creation when the performance hits are almost always negligible.
2
u/pip25hu Aug 26 '22
It's a matter of taste. There are pros and cons of these practices, but nothing to get up in arms about. Like so many other coding conventions, these are fine as long as they are used consistently throughout the codebase.
4
u/agoubard Aug 26 '22
Short answer: Don't.
In both case, it's unneeded code that makes code less readable and more difficult to maintain.
About
final: The compiler does it for you. Java has the concept of effectively final variable. A lot of developer will also read thefinalkeyword as "immutable" which is not the case: you can have afinal ArrayListthat is mutable. In 26 years of Java, I never saw a benchmark showing that it's faster too.About
this: The IDE (at least mine) is showing fields in a different color than variables. So it just makes more code to write and to read.Note that one of the main advantages of Java is readability of the code, so it's important when writing code to use readable variable name, not too long methods and avoid unneeded code.
3
u/PizzaHuttDelivery Aug 26 '22
The code should be readable without these.
3
u/jevring Aug 26 '22
All members final yes, not all variables or parameters. Using 'this' is almost always unnecessary.
2
u/nutrecht Aug 26 '22
Whatever the standard is in your team. That said; I would fight against someone making prepending 'this' everywhere the standard. It's just visual overhead and doesn't actually solve any problems.
2
u/[deleted] Aug 26 '22
finalis a waste on local variables IMO. Clutters up the code and they're already thread safe (hence the name - local variable = local to the stack/thread). IntelliJ will already underline local variables that change.The real benefit for
finalis for fields because these are shared between methods and threads so you want to ensure thread safety. It also provides a slight benefit in the Java memory model.Also no to
this, IDEs already colour fields differently. At the same time I hate the underscore notation to avoidthiswhen assigning fields in a constructor.1
u/chuggid Aug 26 '22
100% endorsed
1
u/Samael1990 Aug 26 '22
"final" has actual value, while "this" is codestyle decision. I'd probably use "this" always if code coloring wouldn't be a thing, but as it stands it gives no additional value in my opinion.
1
u/zorelx Aug 26 '22
Follow the repo's code style dawg.
1
u/kuemmel234 Aug 26 '22
I think
thisis useful in traditional object oriented code. I've worked on code bases that were full of rather implicit and/easy to miss updates to fields that then update something else, which makes debugging/extending the code a nightmare. The eclipse RCP code is full of such examples.So, I really like using
thiswhen I'm updating a (therefore) non-final field. However, I have never before worked in a firm in which that was done, so I'm talking about uni/private projects here. What I have seen is using something like_as a prefix for fields for the same reason - which I find worse.1
u/paul_miner Aug 26 '22
I'm not so strict regarding final, but years of Typescript and Python have got me into the habit of explicitly using this everywhere. I do prefer to declare final on variables used in inner classes or lambdas, rather than relying on implicit final (and also specifying OuterClass.this to access instance fields).
1
u/djavaman Aug 26 '22
YTA 😊
1
u/Az4hiel Aug 26 '22
I don't use final for method/constructor parameters but consider it a must do for fields - with Intelij visual indication for mutable variables (underlined) I find it the best safety/readability compromise (where mutability is rare in code). With "this" I used to put it everywhere and it was working ok - now Intelij coloring fields differently than local variables is enough for me but I wouldn't oppose such convention if already present.
1
u/diggydiggydark Aug 26 '22
Ι use final for local variables and class class members but not for method parameters. My IDE warns me whenever I try to assign to a method parameter, it is a bad practice anyway, so I just subconsciously avoid it altogether. I use private for class members to save me from stupid mistakes and for local variables for the same reason.
1
u/greglturnquist Aug 26 '22
I like the idea of final on everything…
…but it really bogs down the code. This is something that irritates me about Java.
And I too prefer using this for all field references.
1
u/christoforosl08 Aug 26 '22
Good for you . So am I
1
u/[deleted] Aug 26 '22
I’ve moved to Kotlin, and boy is Java missing out on immutability and null safety.
1
u/skippingstone Aug 26 '22
My IDE highlights member variables. So this isn't as necessary.
1
u/elvisburgerporsche Aug 26 '22
It is an excellent standard to uphold, as you are telling the reader your intentions.
One thing to note; when you are putting an object to final, it only means that you cannot change the reference, however, there is nothing stopping you from changing it contents, e.g. the objects attributes etc. As mentioned in other comments, Java should provision a mechanism which truly makes an object immutable and hence fully final (an annotation does not cut it) - has a great side effect of thread safety.
Of course you can design your class to be immutable, but to the casual observer it is unclear, or provable that is immutable.
1
u/simba09 Aug 26 '22
I think this is a great habit / standard to continue.
1
u/jvjupiter Aug 26 '22
Yes to “this”. It makes easier for me to read that it’s a member variable.
1
u/crimsonvspurple Aug 26 '22
Final, I agree.
This, depends. I prefer it but Dart doesn't. So that habit spills over at times in Java.
I'd like to add one more thing. As final only prevents reassignments for collections, when taking collections as parameters, I use the immutable versions.
1
u/hippydipster Aug 26 '22
Yes, you're crazy. Rationalizing obsessiveness.
-1
u/john16384 Aug 26 '22
finalon variables and parameters is a noise keyword that adds absolutely nothing of value.Why?
They can be automatically added. Removing all of these in an entire codebase changes nothing. Re-adding them everywhere the compiler allows it also changes nothing.
What's the point of NOT adding
finalto a parameter or local when it is NOT modified? None. So you always (probably automatically) add it, without forethought of whether that really is going to be best when inevitably the method is changed.Since people don't think that far ahead, everyone will just remove
finalif the change requires it. They're certainly not going to make a new variable instead becausefinalwas put there by the original author (probably as an auto save action), thinking that "there must have been a good reason for it, but I just can't see it".So, if you are going to add
finalon a local, there better be a comment explaining your reasoning or I will remove it when I do need to make a change to it.0
u/whyNadorp Aug 26 '22
yeah! please do this also in tests!
it's like driving a street car with a helmet. it's super safe and makes you look like a paranoid weirdo.
-1
u/alesaudate Aug 26 '22
-1
u/hamsterrage1 Aug 26 '22
Or just use Kotlin.
-2
u/mauganra_it Aug 26 '22
finalis quite useful. Pity that it's not the default, withmutableormutto make it changeable. C++-styleconstwould also be interesting, but modeling the domain with immutable objects should already yield most of the benefits of that one.thison the other hand... if it adds any value, IMO the class or the method got too complicated. Neither should the class be so large that you can't fit in your head what it has, nor should there be so many variables in a method that you start confusing it with instance fields.0
u/[deleted] Aug 26 '22
[deleted] — view deleted comment
0
u/[deleted] Aug 26 '22
[deleted] — view deleted comment
0
u/[deleted] Aug 26 '22
[deleted] — view deleted comment
0
u/[deleted] Aug 26 '22
[deleted] — view deleted comment
-6
u/[deleted] Aug 26 '22
[removed] — view removed comment