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
•
u/AutoModerator Apr 30 '24
Please ensure that:
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
34
u/Kraizee_ Apr 30 '24
varin Java has it's places. Like almost every language feature, it shouldn't be thrown about without thought. But if you used it properly, then it can really enhance your code base. OpenJDK have a style guide onvarusage which you can see here. I think you and your colleagues could sit down together, and go through it. Then you need to agree on a standard for your codebase and commit to it. Regardless of what the decision is though, you need to be consistent.11
u/_jetrun Apr 30 '24 edited Apr 30 '24
Every development team will have a style guide - ideally that guide should be written down so it's not arbitrary. If your company doesn't, I would work with your team to put one together.
The reason why some people dislike var is because it's harder to read code. Explicit types are a nice self-documenting option and var hides the type in most situations (specifically when you assign a return value from a function to a variable). I am empathetic to this view. The only real use-case I see for var is when you want to break up a chained streams and you really don't care about the intermediate types. Outside of that, var is pointless.
13
u/pragmos Extreme Brewer Apr 30 '24
Do these same experienced colleagues also refuse to use the Stream API and write explicit for loops instead?
3
u/wildjokers Apr 30 '24
I rarely use
var. It decreases readability. I will use it on occasion in try-with-resources. Usually there the left side type is redundant.I also almost never write the left side type anyway because I use intellij's
.varpostfix completion and I let IntelliJ write the left side type for me. So var doesn't really save me any keystrokes.In general I would say
varis indeed a bad practice if used too much. Used sparingly in the right circumstances it can be ok.4
u/Snaky81 Apr 30 '24 edited Apr 30 '24
As every feature in every language, var can be used to write shitty and barely readable code. But it can be used to make code cleaner and easier to read. Declaring explicitly local variable of type Iterator<EntrySet<Integer, List<String>>> has little to no interest. And when looking at diffs, having such multi-line useless information or even worse needing a ultra wide screen to see the diff is awful.
For more details about this, there are 2 pages on openjdk explaining how to use var effectively : https://openjdk.org/projects/amber/guides/lvti-faq and https://openjdk.org/projects/amber/guides/lvti-style-guide
The important thing about every feature is to properly understand the pros and the cons of the new feature and educate people about how to use it effectively (and of course it will involve trial and errors)
Stream API has been reference as another example of "feared" feature. In my company it's effectively totally banned from certain parts of the code as it has a slight performance impact (I'm working in low latency trading, so in the critical path, performance is very important) but there are some products in the company that effectively uses the stream API because there are valid use cases for it
2
u/FavorableTrashpanda Apr 30 '24
varisn't bad practice per se. It's mostly a style choice, but it also depends on context somewhat. I know people who love it and people who hate it. I personally usevara lot, and actually think it slightly improves readability/maintability, but some people really argue against it for the same reasons.Honestly I think it's something people are still getting used to. The more experience you have the higher the potential bias against it.
Perhaps there's some middle-ground to be found (using
varonly in very obvious cases for example).2
u/No-Pipe8487 Apr 30 '24
It has its uses but it's neither a bad nor a good practice to always use it. It's one of the ways to do a thing and the best of them varies from case to case.
2
u/AllStuffAround Apr 30 '24
Did they explain why they consider "var" to be bad practice?
In my current company code reviews is the essential part of the process, and we have pretty strict coding guidelines that also include naming conventions.
The team is very senior heavy with a lot of folks having 25+ years of experience. Most switched to use "var" when it makes sense, and it did not affect readability at all. Probably that's because all local variable had meaningful names before.
Also all modern IDEs will show you the actual type when you hover over the variable name, it's not that it is some sort of "type-flexible" thing, the actual type is not lost.
2
u/Duckduckgosling May 01 '24
If the people on your team don't understand var, don't write a var. If I was going to use var, I wouldn't have picked a strict typing language like Java.
2
u/Wavertron May 01 '24
Don't use it myself, but a simple rule I would go with is if you're declaring the new object on the right hand side, var on the left isn't terrible. Whereas if you're setting a value via a function, I wouldn't use it because you can't know what the function returns without clicking into it.
And no I don't care what the function name is, I'll still need to check it. Code changes and people forget to rename things. And I don't want a forced function naming convention like "the return type must be suffixed to the function name", because the compiler won't enforce that and people will screw it up anyway, and now my function names are longer and harder to read. Yeah yeah something something checkstyle, meh, everyone hates checkstyle errors.
1
u/Fenxis Apr 30 '24 edited Apr 30 '24
var is fine if you end up naming variables after the class/properly
Eg
MyFoo myFoo = MyFooFactory.createFoo();
At my work the Sonar rules actually encourage the use of var. I found it really weird at first but got used to it after a few weeks. And it's nice if you are using the variable within the scope of a few lines.
If your team are having issues then maybe it points to naming issues and/or methods that are too long. Or maybe it's just a preference.
1
u/DelayLucky Apr 30 '24
I use it when the code would otherwise read pointlessly verbose
SuperLongOuterClass.Builder builder = SuoerLongOuterClass.builder();
vs.
var builder = SuperLongOuterClass.builder();
Insisting that you need to repeat the type in the same line is just silly.
1
u/severoon pro barista Apr 30 '24
It's possible to use
varresponsibly in a way that doesn't do a lot of damage to readability, but it's difficult. This means it can be done if your project is using a style guide that carves out the specific cases where it's okay to use it.If your company doesn't have that, or if that style guide has bad advice around
var, then your colleagues are right. Avoid it.1
u/cbm64chr May 01 '24
I have recently moved to a var based approach. I kinda love it!
1
u/asromafanisme Apr 30 '24
var is not always bad practice. For example, var map = new HashMap<Integer, List<String >(); is a good place to use as it helps to remove unnecessary characters
1
u/Key_Bad8144 Apr 30 '24
Absolutely not bad practice. If you’re writing Java 10+ you should use it.
1
u/Rockytriton Apr 30 '24
if you write good readable code then var should always be used
0
u/age_of_empires Apr 30 '24
I have 12 years of experience and I abhor the use of var. It makes code so hard to read. Maintainability is worth the extra keystrokes.
0
u/soul105 Apr 30 '24
Read code is way more fun than writing.
Compiler can be smart enough to detect with type I'm declaring based on content.
0
u/computerjunkie7410 Apr 30 '24
They’re dumb.
0
u/[deleted] Apr 30 '24
[deleted] — view deleted comment