r/javahelp • • Mar 30 '20

Why was var added?

All it does is make code trickier to read and tempt the programmer to pay less attention to the type of his variable. Another way to not write clean code.

It seems like a downgrade, why was it added? Is it considered a valuable addition to the language?

For context, https://openjdk.java.net/projects/amber/LVTIFAQ.html answers this as making Classname variableName=new Classname(); shorter. Ok, then why not make it : Classname variableName=new .(); It's shorter and no conflicts with existing variable names. Nor would you have to be aware of caveats like "this can't be used as a parameter".

36 Upvotes

17 comments sorted by

19

u/morhp Professional Developer Mar 30 '20

Sure, you can abuse var, but for some complicated types it's very helpful. Also it enables you to call methods on anonymous types:

public void test() {
	var foo = new Object() {
		void test() {
			System.out.println("test");
		}
	};
	foo.test();
}

You can't do that if you write Object foo = ...;

4

u/Rygir Mar 30 '20

Interesting example, thanks!

8

u/itisafeature Mar 30 '20

Java's verbosity is one of the reasons I like it, so I am inclined to think adding it isn't necessarily a positive.

Your suggestion of Classname variableName=new .(); isn't a good one though. For one, new is not the only thing that can go on the right-hand side. For example: var c = Calendar.getInstance();

0

u/Rygir Mar 30 '20

I didn't mean to imply it has exactly the same functionality, but that it would give the one benefit of shortening instantiation where you have redundancy without the drawbacks.

Personally, I like to know what type a method is returning. Even though your example strongly implies that the instance is a Calendar object, it could be something else... perhaps even a derived class making it very confusing down the line because treating it as a Calendar would work but the type wouldn't be what you expected.

In my opinion it would be an advantage if it doesn't work for method calls - which is why I asked the question. Var just doesn't mesh with the practices I learned for clean code.

My solution avoids limitations like having to make var a reserved type name, or making multiple variable declarations (would only have one source to infer from, left of the "="), or using it with null (you wouldn't be able to), or causing confusing that the type can change. And it would be logical that it's always initialized ... Because that's what new does.

2

u/mrBr0wn_93 Mar 30 '20

I didn't mean to imply it has exactly the same functionality, but that it would give the one benefit of shortening instantiation where you have redundancy without the drawbacks.

But has its own drawbacks, eg List<X> xs = .(). Any isn't useable in many cases var plays really nice, like for (var person : persons).

Even though your example strongly implies that the instance is a Calendar object, it could be something else... perhaps even a derived class making it very confusing down the line because treating it as a Calendar would work but the type wouldn't be what you expected.

You also don't know wether you use a derived class if you write Calendar c = Calendar.getInstance();, that doesn't change with var.

My solution avoids limitations like having to make var a reserved type name

Did you ever encounter a type named var? If so - good it's forbidden now ;)

or making multiple variable declarations (would only have one source to infer from, left of the "=")

When do you need to make multiple variable declarations cause of var?

using it with null (you wouldn't be able to)

You are also unable to use var with null, or what do you mean?

causing confusing that the type can change

In my experience it isn't confusing at all. The type only can change if the return-type of a method is changed. If it's compatible (like List to ArrayList) nothing happens, otherwise it throws compile-errors. Same would happen without var.

1

u/Rygir Mar 30 '20

List<> has a problem with var in that makes it a List<Object> (which is often not what the coder intended according to this OCP course material).

I like your var person example that is nice because then you don't write Person p:Persons .

My point was that if the original coder knew he was getting a subclass of calendar he would have written SubclassOfCalendar =Calendar.getInstance(); and everyone reading the code afterward couldn't make a mistake.

And it's just ugly that var isn't part of the reserved words, but only for types. It's not uniform which means more exceptions to rules to remember.

You can't use var in multiple variable declarations.

Indeed you cannot use var with null which is apparently confusing enough people that they include as examination matter in the OCP exam. In my suggestion you wouldn't even be able to write that, let alone be confused by it.

And by type changing they (OCP exam) mean like in javascript, non static typing. It's the same keyword. In java it doesn't really add functionality, it just obfuscates the actual type and saves a few keystrokes. In other languages it does black magic.

1

u/thecuseisloose Do you even Java, bro? Mar 30 '20

The type the method is returning is defined in the method definition

4

u/Kraizee_ Mar 30 '20

If you read the link you posted you'll see that they accept people will inevitably abuse var and write shitty code. Just like people abuse almost every other language feature. The example you suggest simply doesn't work. Aside from it being a peculiar syntax, there are other problems such as what happens in the case of List<String> myList = new .();

They've also published a style guide as to where and when you should use it https://openjdk.java.net/projects/amber/LVTIstyle.html

var is a fundamentally good addition to the language for reducing verbosity in a nice way, providing that you use it properly and understand when it isn't appropriate.

-1

u/Rygir Mar 30 '20

You wouldn't be able to use var when using interfaces either since you can't new an interface.

For clarity, you understand I was using a fictional syntax example?

The part that makes me wonder is that this feature is essentially only "save a few keystrokes and in return obfuscate your type". I find this a strange trade-off to make and officially support.

2

u/caboosetp Private Java/Code Tutor Mar 31 '20

You can use var when using interfaces. If a function returns an interface, then a variable declared with var will be typed to the interface just as if you typed the interface name.

If you do want a variable type to not match the object, such as when you want an interface typed variable and an implemented class object being stored in it, you would not be able to use var.

Var is a shortcut for when the types should match. It's basically shorthand for, "what he said"

0

u/Kraizee_ Mar 31 '20

I knew you'd try pick up on that. It was simply to demonstrate how poorly thought out your alternative is. It seems to me you made this post to find people that will agree with you, rather than have you learn something. Read the link you posted and the style guide I linked. If you really wish to keep hating and misunderstanding var then so be it.

4

u/snot3353 COMPUTERS!!! Mar 30 '20

Did you check the examples section near the bottom of this? https://openjdk.java.net/projects/amber/LVTIstyle.html

It has very concrete examples showing why it was added and where the benefits are. The rest of the page details scenarios where you should be careful about using this feature. It's up to developers to adhere to that advice.

1

u/Rygir Mar 30 '20

Yes, but I felt it was strange to add a feature that by definition obfuscates the type of a variable in exchange for saving a few keystrokes. This goes against what clean coding standards usually say about things like variable and type names.

That said I can see there are places where there is redundancy and you don't miss anything, I'm just surprised the designers of java thought it was a good idea to make this trade-off.

30

u/thecuseisloose Do you even Java, bro? Mar 30 '20

It was added because in essence, Java already knows the type of the variable at compile time. This is why it's restricted to local variables only. Saying var x = someMethod() can only return one type, so java can infer that type and replace var with the correct type. With non-generic types it doesn't have that great of a benefit, but it's reduces a lot of boilerplate by saying var x = someMethod() instead of List<Map<String,Object>> x = someMethod().

If you don't like the feature, you are not forced to use it. But as a daily java developer, I hate when I am working on a Java 8 project and unable to use this feature

1

u/proskillz Some Skillz Mar 31 '20

My best guess is many engineers are stuck in legacy Java codebases but really like the capabilities of Kotlin and Scala, so the Java language is trying to add some of the features you get for free in those languages.

1

u/Offifee Mar 31 '20

YourStandardEnterpriseCodeClass yourStandardEnterpriseCodeClass = new YourStandardEnterpriseCodeClass();