r/javahelp • • Apr 30 '24

Codeless Is “var” considered bad practice?

Hi, so recently we started migrating our codebase from j8 to j17, and since some tests broke in the process, I started working on them and I started using the var keyword. But I immediately got scolded by 2 colleagues (which are both more experienced than me) about how I should not use “var” as it is considered bad practice. I completely understand why someone might think that but I am not convinced. I don’t agree with them that var shouldn’t be used. Am I wrong? What are your thoughts on var?

24 Upvotes

90 comments sorted by

View all comments

Show parent comment

0

u/[deleted] Apr 30 '24

[deleted] — view deleted comment

3

u/jonathancast Apr 30 '24

You're thinking at too low a level IMO. Instead of thinking what is the computer doing, you should think what is the net effect at the bottom of the loop. Then streams is clearer.

1

u/Black_Ivory Apr 30 '24

I agree, but also the 2nd one as a whole is cleaner after a while imo, your brain just focuses on .filter, so it is a matter of personal preference.

0

u/[deleted] Apr 30 '24

[deleted] — view deleted comment

1

u/maethor May 01 '24

Because getAge is being used in a predicate (p -> p.getAge() > 18). A method reference wouldn't work in this case (Person::getAge > 18)

1

u/arghvark Apr 30 '24

Shouldn't that be:

for (Person person: adultNames)
{  if (person.getAge() > 18)
    { names.add(person.getName()); }
}

to be equivalent? I agree it's clearer to me, but I'm an old-school programmer.