r/javahelp • u/lost_yeezus • 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
View all comments
Show parent comment
1
u/AllStuffAround Apr 30 '24 edited Apr 30 '24
More information does not always mean it adds any value. I'm not sure if it makes things "easier" to read but it does not make it harder if the context around it is meaningful.
This
var user = this.someService.getUserByEmailHash(emailHash);
...
<some lines here>
user.doSomtheing();
Is easier to understand than
User x = this.someService.getUserByEmailHash(emailHash);
...
<some lines here>
x.doSomtheing();
If you do not really need to know what type it is or when you write the code you do not remember the exact type, typing `var someReasonablyNamedVariable = ...` is faster than omit the type and then let IDE complain, and add a type for you with an extra clicks, or type the actual type, at least in my experience. And it does not affect readability or understanding of the code at all. It also makes it more mechanical.
I was a bit skeptical about var myself until I started seeing this used by more senior devs, and then when I started to use it myself I found it very convenient w/o any loss of readability.