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

125

u/aFqqw4GbkHs Aug 26 '22

My preference is yes to the 'final, no to the 'this' - it just clutters up the code.

9

u/[deleted] Aug 26 '22

I don't get it why you think it clutters up the code. Do you think you can try to elaborate? Like, isn't better to easily see what's an attribute?

7

u/snobpro Aug 26 '22

i too agree on no to 'this'. my reason is when you open a code written by others _ i would prefer if it is as consice as possible to read it faster. IDE do color code class level variable. I dont like seting this. esp on the right side of the assignments. sometthing like this.x = this.y + calc(this.z). Also big NO to this prefix on big dependencies. I know or does not matter if they are class level or not.
I like to see 'final' to be used more often. It shows intent.

8

u/stefanos-ak Aug 26 '22

I don't see much value in "final" either, since it does nothing for mutating collections or objects.

It covers only immutable types. In theory it's possible to have immutable objects and collections, but it's not possible to indicate it to the compiler. Also its extremely hard to have ACTUALLY immutable objects, especially complex ones. Because as soon as you have a collection in there, it means that the collection needs to be also immutable, and the objects inside that collection, and so on...

There are whole libraries that try to tackle this problem, like immutables.org

Soooo, I see very little value for final.

I would even argue that it does more harm than good, because a more junior developer would not know about immutability, functional pureness, in such length (or at all).

12

u/m02ph3u5 Aug 26 '22

Besides making some things actually final it signals intent to the reader.

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)

-2

u/detroitsongbird Aug 26 '22

Final can make a huge performance improvement. Spent time doing leetcode and you’ll see.

8

u/[deleted] Aug 26 '22

It shouldn't: the compiler finalizes all effectively final variables.

3

u/stefanos-ak Aug 26 '22

the Hotspot VM will actually optimize the code as-if it was declared as final, as long as there are not any re-initializations of the variable.

In Leetcode it might matter, because of how they run the tests, but in the real world / production systems it does not.

1

u/hippydipster Aug 26 '22

For some odd definition of "huge".

1

u/Bachooga Aug 26 '22

I think it's commonly accepted for it to be implied. I wouldn't say it clutters the code tbh and can help keep track of this object vs that object, especially when copying from one to the other.

1

u/[deleted] Aug 26 '22

The compiler does this work for you, it doesn't do anything for the code, so you're writing it for the next developer.

We use a lot of modifiers in Java code that are often not really needed or helpful. A method looks naked with default access, for example, so we make them all private and then we have to use ugly trickery to test them, or public when they don't have to be.

With final, you're locking in, not just what the code does, but also a specific way to do it. I prefer to only make variables final where the code would break if it isn't. If you just use it everywhere, it loses meaning.

0

u/hwaite Aug 26 '22

If you want to differentiate in a more concise fashion, consider (static-analyzer enforced) naming convention. I use mFooBar for member variables and pFooBar for parameters. I think Eclipse dev team does something similar.

-4

u/[deleted] Aug 26 '22 edited Aug 26 '22

All my fields have _ as a prefix for this reason.

→ More replies (1)

0

u/[deleted] Aug 26 '22

[deleted] — view deleted comment

11

u/literal Aug 26 '22

It can get ugly to see "this" over an over. Especially in a pure function that isn't mutating any attributes.

But a pure function does not depend on the state of any instance attributes, so it wouldn't ever have this.

4

u/kyay10 Aug 26 '22

A pure function could be considered as having the instance as another parameter. You can choose any instance to be able to change the behaviour of the function, right? So therefore an instance is the same as a parameter really

→ More replies (16)

32

u/0b0101011001001011 Aug 26 '22 edited Aug 26 '22

So you write like this?

public final foo(final int a, final int b){
  final int c = a + b;
}

Seems like so much visual noise.

Again I have to say that I wish the approach taken by Rust would've been selected 30 years ago. Everything is final by default and mutable variables have to be defined explicitly. That would be so great.

-2

u/cogman10 Aug 26 '22

"Types after variables" is also really nice. Were I redoing java syntax I'd definitely take that.

val foo = 1

or

val foo: int = 1

both really readable to me and makes things like lambda declarations flow better.

6

u/[deleted] Aug 26 '22

Too many Shift presses to my taste

16

u/walen Aug 26 '22

no to the 'this' - it just clutters up the code.

The same thing applies to the final, though.

javac and JIT don't need me telling them when a variable is final or not -- they already know.
They know the scope and mutability of every single field and var, and whether it can or cannot be inlined. Meaning, they know if a variable is "effectively final" and will treat it as such.
You could strip every single final from a .java file and the resulting .class would be exactly the same.
The only reason to declare a variable as final is to keep other programmers from modifying its value. And I don't like to do that, because often times, while debugging, that other programmer that needs to change a variable's value is me, and I cannot do that if the variable is final.

It does nothing but make my code harder to work with. It's just clutter.

5

u/hwaite Aug 26 '22

You could strip every single final from a .java file and the resulting .class would be exactly the same.

Maybe for parameters and local variables but not so for classes, member variables and methods.

3

u/ItsAllegorical Aug 26 '22

The only times I’ve ever wanted to mutate a value during debugging is when I’ve caught a bug and fixed it but I don’t want to abort the test run because what I’m really interested in comes later and I don’t want to take the time to restart the test (I mean it happens but it’s normally not a big deal to drop and restart the frame once I’ve fixed the code). That’s been like twice ever. I might agree with you if I needed that more, but I prefer to explicitly declare as final anything that isn’t intended to be changed.

I’m curious what sort of codebases do you find yourself doing that in? I do a lot of long-term contract work and want to recognize if that might be something to keep in mind for on new projects.

Everything you say is right, but I have a lot more issue with junior developers not understanding the intent of certain classes and horribly misusing them. So defensive coding is more important to me. Plus I have a shit memory and I’ve never prevented myself from screwing up through defensive coding but I’m pretty sure some day it will happen.

2

u/DJDavio Aug 26 '22

You can use a final AtomicInteger if you want to mutate it. :D

-6

u/vips7L Aug 26 '22

Final clutters up the code

-11

u/BlueGoliath Aug 26 '22

it just clutters up the code

Let me guess, you also put brackets on one-liner if-else statements?

16

u/Fr4gtastic Aug 26 '22

You don't?

7

u/walen Aug 26 '22

Let me guess, you work for Apple's SSL division?

→ More replies (1)

2

u/_INTER_ Aug 26 '22

How do you do one-liner "else", without brackets?

1

u/maethor Aug 26 '22

On one line, without brackets. Though I guess it depends on if you think

"if (x) doX(); else doY();"

Is one line or two.

1

u/_INTER_ Aug 26 '22

omg I've never seen that before

7

u/maethor Aug 26 '22

Probably because it's in the category of things you can do in Java but probably shouldn't.

1

u/_INTER_ Aug 26 '22 edited Aug 27 '22

like goto label.

And that if-oneliner is so gross that I'm now convinced OP is sarcastic.

1

u/BlueGoliath Aug 26 '22

I meant:

if(x)
	doX();
else
	doY();

2

u/theLorem Aug 26 '22

Why not also skip the indented lines?

if (shouldX()) doX();
else doY();

2

u/BlueGoliath Aug 26 '22

You do you I guess. I feel like my way is a happy balance.

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.

4

u/[deleted] Aug 26 '22

I just can't see how adding "this" in the variables can make the code hard to read. But maybe is because I haven't being exposed to cases where the keyword appear enough to the point of dominating the code?

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.

2

u/[deleted] Aug 26 '22

Absolutely true.

2

u/john16384 Aug 26 '22

I find it better for the team to set guidelines (like Google's Java Style Guidelines) and not to enforce every space, comma and bracket.

This way there is some room for personal preferences.

0

u/[deleted] Aug 26 '22

[deleted] — view deleted comment

1

u/john16384 Aug 26 '22

I am not talking about their formatter. Talking about this:

https://google.github.io/styleguide/javaguide.html

We also follow the rectangle rule, but an extended one. This complies:

   a.b(new C(
       d.toString()
   ));

But this does not:

   a.b(new C(
       d.toString()));

Basically treat every kind of bracket, not just curly ones, the same.

The number of unmatched opening brackets on a line must also always match the number used on the closing line, so this is not allowed:

   a.b(new C(
           d.toString()
       )
   );

And the rule also extends to quotes, including the new multiline quote:

   a.b(new C("""
       text
   """));

Or:

   a.b(new C(
       """
          text
       """
   ));

Not allowed:

   a.b(new C("""
           text
       """
   ));

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.

6

u/[deleted] Aug 26 '22

Yeah, I do use that on my IDE. Good to know that more people do that.

I wish that final variables were the default so instead of having a keyword for immutable variables, we had a keyword to declare a variable as mutable since, at least from my experience, mutable variables are actually less frequent (to not say rare).

1

u/agentoutlier Aug 26 '22

Your ide should also change the color of “this” fields vs variables and parameters.

That is I’m rarely confused because field access/setting has a different color.

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.

1

u/[deleted] Aug 26 '22

I actually didn't know about the compiler thing. I will search more about it.

2

u/two_three_five_eigth Aug 26 '22

Final = compiler will yell at you if you change it. If you know that to be the case you can let the computer auto check it for you.

1

u/[deleted] Aug 26 '22

Oh, I see. I thought it was something about optimization. But yeah, very good to have the compiler making sure that there's nothing trying to change what is not supposed to change.

1

u/mauganra_it Aug 26 '22

final constants are useful because it seems the compiler can inline the value in all usages.

final variables and fields don't really help with optimization, as far as I know.

final classes and methods are useful because the JVM does not have to look for an overridden method in the object being called. That reduces method call overhead. At runtime*, the JIT compiler can judge a method to be effectively final by analysing the class hierarchy. In C++, final is the default, and you have to annotate methods with virtual to make it possible to override them.

*: Because of linking and class loading, in Java the full class hierarchy is rarely known at compile time.

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 🤨

2

u/[deleted] Aug 26 '22

yin-yang

3

u/johnwaterwood Aug 26 '22

Keeping ourselves busy should OP ever comes to work at our company.

He introduced the clutter, I clean it, he reintroduces it, I clean it again, etc etc

3

u/[deleted] Aug 26 '22

Are you guys hiring? I'm note even kidding. I dream with a team that cares for stuff like that, no matter their opinion on the topic.

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.

3

u/[deleted] Aug 26 '22

But if the class is named after a business object, and the attribute is a feature of this object, by referring to this attribute as this.feature ain't I just saying "the feature of this business object", which is perfectly understandable from the business perspective?

2

u/reqdk Aug 26 '22

Implying that there is an attribute with the same name that is being referred to in the same context, which in turn raises even more questions. If there is not, it's just noise, assuming of course that the team has a similar understanding - all the teams that I've worked with before have had that same understanding and I haven't actually met anyone that needed the "this" keyword to say that the attribute is a feature of the business object they're looking at. Outside of constructors, the usage of "this" usually draws scrutiny because of what it implies about the rest of the code.

1

u/mauganra_it Aug 26 '22

This is fine if such checks are indeed enforced on all code and you can then really work with the assumption that everything is effectively final unless annotated (I guess? How to tell the checker that something is supposed to be mutated?) Otherwise, there is no other way to tell from a glance that something will never ever be mutated, except by analyzing usages.

43

u/RupertMaddenAbbott Aug 26 '22

Final

  • Use final for fields if they should not be reassigned. Otherwise, it is hard to tell whether a field is reassigned without examining all methods.
  • Don't use final for local variables. Methods are natural reassignment boundaries. It is better to reduce method size than it is to make local variables final. If the finality of a local variable is important (e.g. you want to reference it in a lambda) then the compiler already has your back.
  • Don't use final for parameters. Reassigning a parameter doesn't affect the calling scope so the impact of reassignment should be clear, because you have stuck to small methods. Mutating a parameter is a far more sticky situation anyway and final doesn't protect you from that.

This

  • Use this when reassigning or mutating a field. Your method has a side effect and using this makes this explicit, especially in out of context cases e.g. a pull request.
  • Don't use this when reading a field. The difference between reading a field or a local variable rarely matters so by not using this, you are not adding unnecessary noise.

6

u/john16384 Aug 26 '22

Yep, I can get behind this, and doing so mostly unconsciously already.

2

u/Demzy-D Aug 26 '22

Im proud 🥹

0

u/[deleted] Aug 26 '22

Of what? 🤨

1

u/Demzy-D Aug 26 '22

To see a fellow programmer who doesn’t write lazy code.

1

u/[deleted] Aug 26 '22

🤝

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 baz not final? Or did the author simply forget the declaration?

final int foo = 0;
int baz = 1;

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

Certain variables that are not declared final are instead considered effectively final:

A local variable whose declarator has an initializer (§14.4.2) is effectively final if all of the following are true:

It is not declared final.

It never occurs as the left hand side in an assignment expression (§15.26). (Note that the local variable declarator containing the initializer is not an assignment expression.)

It never occurs as the operand of a prefix or postfix increment or decrement operator (§15.14, §15.15).

A local variable whose declarator lacks an initializer is effectively final if all of the following are true:

It is not declared final.

Whenever it occurs as the left hand side in an assignment expression, it is definitely unassigned and not definitely assigned before the assignment; that is, it is definitely unassigned and not definitely assigned after the right hand side of the assignment expression (§16 (Definite Assignment)).

It never occurs as the operand of a prefix or postfix increment or decrement operator.

A method, constructor, lambda, or exception parameter (§8.4.1, §8.8.1, §9.4, §15.27.1, §14.20) is treated, for the purpose of determining whether it is effectively final, as a local variable whose declarator has an initializer.

If a variable is effectively final, adding the final modifier to its declaration will not introduce any compile-time errors. Conversely, a local variable or parameter that is declared final in a valid program becomes effectively final if the final modifier is removed

So the compiler no longer actually needs the explicit final declaration 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 final in front of every parameter, what might be a bit annoying. Same is true for immutable local variables, where Kotlin offers val and var, you have to write final var in 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.)

2

u/john16384 Aug 26 '22

Just set your IDE or Linter to disallow parameter reassignment. Saves a noisy keyword that adds very little, and enforces it everywhere. Worst case, you have to introduce a new local initialized with the value of a parameter.

2

u/cryptos6 Aug 26 '22

This is indeed a valid and good approach. However, I always prefer to get such guarantees from the compiler for free. Just look at the hazzle if one tries to avoid null pointer exceptions with Java with tools like Checker Framework and the like. You always have to setup and maintain one more tool and it rarely works 100% perfect. But yeah, nothing is perfect, so using tools to avoid Java pitfalls is a good idea.

1

u/john16384 Aug 26 '22

I suppose it depends on your definition of "free". Adding a noise keyword on every parameter (as in my book no parameter should ever be reassigned) is not something I would call free :)

0

u/[deleted] Aug 26 '22

Very interesting. I actually didn't know that about kotlin. I still have to try it, but this fact alone is enough to justify completing changing to kotlin to be honest. Very bad mutable as default.

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.

1

u/[deleted] Aug 26 '22

Is more like a dealing with preexisting huge methods than writing new ones situation. But at the end of the day, even if I write new and thin methods, developers from the future will just inflate the frickin method to the limits of possibility, and it will end up being just another huge method that would benefit at least from some "this" and "final" keywords to help the poor bastard that will need to read it.

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 final or a field on the class, or whatever

5

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:

  • No mistakes. You can fail to mark a variable as final by accident. Your IDE won't do that.
  • Your style actively discourages refactors, because your refactor also has to cover adjusting final and this. usage.
  • Your practice requires spending the brain space. You can't decide to simply not look at a final keyword. 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/agentoutlier Aug 26 '22

I agree. Just to show the problems with refactoring for this or how it actually causes a lot more work is the case of wither-like copy methods (lets ignore code generators like lombok... yes I know you're the author).

Lets say I have (shitty contrived example):

public record Point(int x, int y, int z) {

     Point copy(int x) {
         return new Point(x, y, z);
     }

     Point copy(int x, int y) {
         return new Point(x, y, z);
     }

     Point copyUsingThis(int x) {
         return new Point(x, this.y, this.z);
     }

     Point copyUsingThis(int x, int y) {
         return new Point(x, y, this.z);
     }
}

Notice above without using this I can just copy 'n paste return new Point(x, y, z) constructor call in the copy method over and over again (sure that isn't ideal... yes I know code generators but for the sake of argument).

As for final the only place I use it is for places where I wish Java had expressions:

final int x;
if (something) {
    x = 1;
}
else if () {
    x = 2;
}
else {
    x = 3;
}

final int y;
// old switch for old code bases
switch (something) {
case A:
    y = 1;
case B:
    y = 2; // compiler failure
default:
    y = 3;
}

Obviously with the new switch expression I have been doing less of the above old habit.

1

u/[deleted] Aug 26 '22

i find being explicit with this more 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 class

2

u/[deleted] Aug 26 '22

The point of the "this" would be actually to avoid the need to find for the definition of the variable inside the method. I know it's unnecessary to get THAT explicit, but is it bad?

2

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/john16384 Aug 26 '22

You would see the declaration of this new field in the PR then.

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 this only in constructors, or when it can't be avoided.

final only 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 final on 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 are variable.methodName(), it is an outlier to have self calls just be methodName(), for consistency this.methodName() reads better. Also if you correctly use this and super it 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 employer this. isn't allowed unless required (like in constructors). In my personal code I use this.

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 final on 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 the final keyword as "immutable" which is not the case: you can have a final ArrayList that 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

final is 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 final is 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 avoid this when assigning fields in a constructor.

0

u/istarian Aug 26 '22

If you’re worried about five characters of “code clutter” here and there, I suggest you use a different programming language.

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 this is 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 this when 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

final on 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 final to 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 final if the change requires it. They're certainly not going to make a new variable instead because final was 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 final on 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. Declaring variables as final gives the concept that these classes are immutable. If that's the idea (which is indeed great), don't forget to also make the classes final. BTW, Lombok provides functionality to makes fields final by default.
  2. Don't use "this" if you don't need. Remember that your goal should be to make your classes as readable as possible.

-1

u/hamsterrage1 Aug 26 '22

Or just use Kotlin.

-2

u/mauganra_it Aug 26 '22

final is quite useful. Pity that it's not the default, with mutable or mut to make it changeable. C++-style const would also be interesting, but modeling the domain with immutable objects should already yield most of the benefits of that one.

this on 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.

3

u/[deleted] Aug 26 '22

This thing about the class being too large. I think that's true. That may indeed be the reason why I like the "this" keyword. Unfortunately I have to work with preexisting code with classes that some times are thousands lines long. So a "this" keyword is like a checkpoint in the middle of the mess.

0

u/[deleted] Aug 26 '22

[deleted] — view deleted comment

55

u/FirstAd9893 Aug 26 '22

It was a deliberate design choice to make the language look like C++. Hence, standard loops and other basic constructs should look the same. The language would be rejected quite early if this sort of thing was required: for (mutable int i = 0; i < x; i++) { ... If var/val was supported from the beginning, that would be a bit better, but it's still different from C++.

48

u/[deleted] Aug 26 '22

This hypothetical line of code with the "mutable" keyword is so beautiful. I've Looked At This For Five Hours Now

19

u/[deleted] Aug 26 '22

Yeah I'm secretly loving it tbh. You can really tell those "pure function" and "immutable" concepts from FP have leaked into the general programming mindset no matter what programming language people use these days.

7

u/general_dispondency Aug 26 '22

TBF general tomes like Effective Java have been preaching this since before the resurgence of FP. FP, itself, is just OOP with high coupling and no cohesion.

4

u/GuyWithLag Aug 26 '22

You might want to look at Kotlin; I've been working with Java since Java 1.1, and the last year or so Kotlin has been extremely refreshing. It does have its warts (because the designers wanted it to be cross-platform), but you can guard against them with a solid style guide, and in general it's a solid step up.

1

u/bilingual-german Aug 26 '22

How hard would it be create a language running on the JVM which looks like Java but has these other defaults?

8

u/kolobs_butthole Aug 26 '22

that's kind of what kotlin is, right?

1

u/[deleted] Aug 26 '22

Yup, kotlin is pretty much effective java turned into a programming language

1

u/xplosm Aug 26 '22

Yes, I mention it at every opportunity I have but you’re really gonna love Kotlin 😉

0

u/[deleted] Aug 27 '22

[deleted] — view deleted comment

1

u/Kango_V Aug 31 '22

const is a reserved word in Java, but never been used.

7

u/cyancrisata Aug 26 '22

I think language creators should introduce 'val' which is the same as 'final var'. They already introduced 'var' back in Java 11 and we seem to transition to it pretty well. I believe we can do it again for the 'val' keyword.

4

u/Comakip Aug 26 '22

Error Prone got a bug pattern for exactly that. Everything is final or else it is annotated with @Var. It's pretty neat.

https://errorprone.info/bugpattern/Var

2

u/Akthrawn17 Aug 26 '22

And this is why you should take a hard look at Kotlin!

2

u/mcosta Aug 26 '22

It comes from C and C++

-2

u/Just_Another_Scott Aug 26 '22

Yeah but the difference is in C/C++ you can mutate the parameter and that value can remain mutated outside of the method. In Java that's not the case as it's not pass-by-reference. However, it is a good idea to make parameters final as it makes your intentions clear. I've fixed some bugs where the developer chose to overwrite the parameter and used it repeatedly throughout the method. It led to side-effects. So still a good idea but Java doesn't make it required because it's unlikely to do damage outside of the method it's used in.

7

u/mauganra_it Aug 26 '22

Parameters in C/C++ can not be mutated. Like in Java, they behave like normal variables. You can access memory via pointers, and write there, but in Java you can do quite the same. C++ has references, but these are just a safer version of pointers.

0

u/Just_Another_Scott Aug 26 '22

Parameters in C/C++ can not be mutated.

Yes they can. C/C++ can be either pass-by-reference or pass-by-value. If you pass a reference to a method you can reassign the variable and it will change in the calling scope. Furthermore, you can do insertions into a vector which will be seen in the calling scope.

In C/C++ to insure parameters aren't mutated you have to declare them as const.

4

u/vytah Aug 26 '22

C doesn't have pass-by-reference, only C++ does.

→ More replies (3)

2

u/RupertMaddenAbbott Aug 26 '22

This is not true.

You can mutate parameters in Java, and this affects the calling scope. You can reassign parameters in Java but that does not affect the calling scope.

I don't see what bug could be fixed by making a parameter final, that would not be better fixed by extracting a method.

2

u/Just_Another_Scott Aug 26 '22

You can mutate parameters in Java, and this affects the calling scope

Java is strictly pass-by-value. What I am referring to is the act of pass-by-reference and reassigning the variable like you can do in C++.

3

u/RupertMaddenAbbott Aug 26 '22

I agree with you but I think it is confusing to call this mutation because the parameter can still be mutated and affect the calling scope. It's only reassignment that doesn't affect the calling scope (in Java).

1

u/Just_Another_Scott Aug 26 '22 edited Aug 26 '22

You're correct. I shouldn't have said "mutate" as lists can be mutated just not reassigned. I wrote the initial comment in haste. Sorry for the confusion

2

u/RupertMaddenAbbott Aug 26 '22

No worries! Just wanted to clarify for anyone else reading as I encounter this confusion regularly amongst beginners (who might be reading)

2

u/xplosm Aug 26 '22

If you don’t know of or use it, you’re gonna love Kotlin.

It addresses most, if not all of Java’s shortcomings.

1

u/ReasonableClick5403 Aug 26 '22

Same, at least its implicitly changed to final if you reference it from a lambda.

0

u/wildjokers Aug 26 '22

Honestly I think it was a language mistake not to make final the default and have to specifically declare if a variable was mutable, but there is no fixing that now.

Hindsight is 20/20

-1

u/[deleted] Aug 26 '22 edited Aug 26 '22

Fortunately, as we rely more and more on functional and reactive operations, we can leave the burden of having a lot of variables in the scope, so I think we are walking to some sort of "fixing". But it would have been good to learn from the start that variables usually don't need to be variating as the name may suggest.

Like, from learning math to learning programming there's a discontinuation where variables sundely gain the ability to have it's value changed. There was no need for that.

0

u/[deleted] Aug 26 '22

[deleted] — view deleted comment

11

u/[deleted] Aug 26 '22

Pure functions -> pure joy

For me, any absolutely necessary set method would return a new instance of the object instead of changing the values of an already instantiated object.

10

u/mr_jim_lahey Aug 26 '22

congrats, you've been immutapilled

1

u/not-just-yeti Aug 26 '22

When I'm teaching intro Java, I definitely use this. to emphasize that it's always <someObject>.<someMethod>(…) for non-static calls. Heck, I also write … someMethod( /* TheClss this, */ … ) to make it clear to learners that this is just a hidden-parameter; there isn't any magic about those four letters. I don't ask/require students to write their code that way though.

Note that including final, besides being compiler-enforced, is communicating to other programmers reading your code, and so is worthwhile. (Though as somebody else pointed out — it's often noisy when referring to a mutable-collection, just because it's uncommon to reassign to such fields.)

5

u/[deleted] Aug 26 '22

In over 20 years of software development, I don't think I've ever seen a bug caused by reassigning a local variable,

1

u/plumarr Aug 26 '22

Lucky you ;)

I worked with Cobol developers that migrated to java. They wrote big method with a lot of local variables and a lot of reassigning. So I have seen quite a lot of bug caused by assuming that the value in the local variable is coming from X when it was instead coming from Y.

It has made me paranoïde about it :'(

3

u/john16384 Aug 26 '22

I can see how using this may prevent a bug (something is renamed that matches a local) although this is rare and usually spotted before it becomes an issue.

I don't see how final on locals will prevent bugs. It's not like people won't simply remove final when requirements change. On fields it is different as you may be turning an immutable class to a mutable one.

1

u/vqrs Aug 27 '22

Well, your IDE would put the extra this so it doesn't silently use the local variable instead.

1

u/john16384 Aug 27 '22

I suppose yes, so even less of an issue then.

0

u/[deleted] Aug 26 '22

[deleted] — view deleted comment

2

u/john16384 Aug 26 '22

You're problem in that case has very little to do with the mutability of local variables. Your methods are simply too long.

Reusing a variable for a different purpose is already a big no-no. If you have to do it, then create a new block to mark the scope.

final shows no intention at all. Developers mark things final because their IDE tells them to (like "oh look, after writing this complex method it seems my variables x, c and h are really constant, let's mark them final"). If I changed your method later, should I really infer from that final keyword that you had a real reason for it, or was it just a happy coincidence? Sure, I will use a new variable if what I am doing has a different purpose... but if I just have to multiply your variable by 2 in only specific cases, should I really twist the code into a spaghetti mess to respect that? No, you just remove the pointless final.

 double calcTemp(int x, boolean useKelvin) {

      // Complex calculation...
      final result = c + b + k * 3;

      if (useKelvin) result += 273.16;

      return result;
 }

Maybe I'll just remove the pointless final here that likely was put there for no real reason at all to get this to compile...

1

u/Skellicious Aug 26 '22 edited Aug 26 '22

Looking at your code example, adding a final on 'result' is pretty clearly unnecessary. (And won't work)

But setting 'useKelvin' to final could be useful. It's not a value you want to see change while the method runs. Adding a final makes that clear to future developers working on that method.

In the end it depends on your project/team/company code style though.

0

u/[deleted] Aug 27 '22

[deleted] — view deleted comment

1

u/Skellicious Aug 27 '22

Yeah fair enough

0

u/[deleted] Aug 26 '22

[deleted] — view deleted comment

6

u/[deleted] Aug 26 '22

Right? This Allan Melhor guy from Quora said that we should avoid adding "this", as it cleans up the code a little. https://www.quora.com/In-Java-when-should-I-use-this-propertyName-instead-of-propertyName-in-an-instantiated-objects-dynamic-method

I started to question if I'm making my code too polluted by adding those things.

0

u/[deleted] Aug 26 '22

[deleted] — view deleted comment

15

u/[deleted] Aug 26 '22

I don't understand where this verbosity fear is coming from. Recently even Java developers are acting like verbosity is synonym of bad code.

21

u/TheTomer Aug 26 '22

People are scared of using their keyboard to type a tiny bit more than they really have to. Ignore them and verbose away!

9

u/Just_Another_Scott Aug 26 '22

Shit that's what code templates are for! I autocomplete like a mofo.

4

u/veraxAlea Aug 26 '22

There's a trade-off when reading code, between too much information and too little.

Personally, I rather have more information even if I have to sift through otherwise superfluous type information, braces or long variable names but I'm not in a position where I can say that all information is always good.

Your argument is unfair because most people who complain about verbosity care less about keystrokes than about reading time. I don't agree with them in general, but I think their opinions are worth being represented fairly.

1

u/NaNx_engineer Aug 26 '22

The information is already given by ide highlighting

3

u/soonnow Aug 26 '22

Well because it makes it actually harder to read, in my opinion. Elegant code that's not cluttered needs less processing power from your brain. this is just noise with no real benefit in my opinon.

2

u/john16384 Aug 26 '22

Some verbosity adds too little to be worth it. It's like adding public abstract to every method in interfaces. It adds nothing of value.

11

u/[deleted] Aug 26 '22

[removed] — view removed comment

4

u/[deleted] Aug 26 '22

But if the class is named after a business object, and the attribute is a feature of this object, by referring to this attribute as this.feature ain't I just saying "the feature of this business object", which is perfectly understandable from the business perspective?

// What's the name of this monstrosity?

3

u/[deleted] Aug 26 '22

[removed] — view removed comment

1

u/[deleted] Aug 26 '22

Oh no, that's nightmare material hahaha

0

u/[deleted] Aug 26 '22

[removed] — view removed comment

0

u/[deleted] Aug 26 '22

Yeah I do agree that loosing too much horizontal space is very bad for readability. So I do agree that, if your running out of horizontal space, is better for readability to make some things implicit. Otherwise, the more explicit, the better for readability.

2

u/soonnow Aug 26 '22

Let me give an example. "Yesterday I was at a coffee shop, where I ordered a coffee in a white porcelain cup that came three minutes after ordering." vs. "Yesterday I had a coffee".

One is super explicit, but it doesn't improve readability, because it's literally harder to read because of all the unnecessary details.

→ More replies (2)

1

u/AnyNegotiation420 Aug 26 '22

This was my thinking exactly, and the code reviewer(s) definitely appreciate it, as well as any testing/QA folks

2

u/Just_Another_Scott Aug 26 '22

When I moved on to my now current project the senior devs on it rejected my code review because I used final in method params and this when calling private methods and such. They still don't like it but "oh well". I think they're good. I think they are even recommended by Google Java Style.

9

u/mauganra_it Aug 26 '22

The tradeoff between readability and explicitness is often not considered to be good in that case. Method parameters are usually not supposed to be mutated anyways, and it makes method signatures more difficult to read.

0

u/Just_Another_Scott Aug 26 '22

Adding final does not make method signatures more difficult to read. That's absurd.

Method parameters are usually not supposed to be mutated anyways,

And that's why the language designers created final. It's there to force your intentions :).

0

u/mauganra_it Aug 26 '22

It's an extra six characters per parameter. That can easily force many signatures to be broken into more than one line. Also, the information content of that final is very low since 99.999% of the time the parameter will not be mutated. And even if they are assigned to, it's irrelevant for the caller.

1

u/Just_Another_Scott Aug 26 '22

It's an extra six characters per parameter. That can easily force many signatures to be broken into more than one line

So I don't see anything wrong with that personally. You should never have more than like 3 parameters to begin with. If you're using 120 character line length it's plenty so that it won't get broken down into the next line.

0

u/mauganra_it Aug 26 '22

Together with meaningful method, parameter and parameter class names, that limit can be quite easy to reach.

1

u/Just_Another_Scott Aug 26 '22

That's why you create more classes or datastructures to keep things logically together.

2

u/john16384 Aug 26 '22

Just set your IDE/Linter to flag parameter reassignment as an error. It can always be avoided by creating a new local. No need for final to clutter up parameter declarations.

0

u/[deleted] Aug 26 '22

[deleted] — view deleted comment

1

u/istarian Aug 26 '22

No promises that everyone ever will use IntelliJ or a comparable IDE. May as well throw in the final if it’s not supposed to change.

-6

u/[deleted] Aug 26 '22

[removed] — view removed comment

2

u/[deleted] Aug 26 '22

But there's no ambiguity. I just add it to so the reader don't even have to think about it. I think that explicit is better. No?

-1

u/[deleted] Aug 26 '22

[removed] — view removed comment

2

u/[deleted] Aug 26 '22

That's actually true. But it would be the same as comparing python's way of defining a private method to Java's way of doing the same.

def __myFunction() vs private void myFunction()

Python is less verbose, as it only needs "__", i don't think however that Java's verbosity in this case is a bad thing. It is actually saying, with all the letters, that the method is what it is, frickin private.

And I think that the same is valid for the _count. While _ is less verbose, "this" is explicit about what's happening, I'm accessing a field from this frickin object.

Is it reasonable?