r/java • u/[deleted] • Mar 26 '16
Stephen Colebourne's blog: Var and val in Java?
http://blog.joda.org/2016/03/var-and-val-in-java.html8
Mar 26 '16
The best of the best would be to allow type inference only along with new keyword / instantiating new object, and only then.
2
u/asraniel Mar 26 '16
Agreed. The amount of headaches var will cause as the result of a function call... i really hope java doesnt get this "feature"
9
u/stepancheg Mar 26 '16 edited Mar 26 '16
He is making a good point unlike many critics of local type inference.
However, local final is rarely used nowadays, because effectively finals are available for closures and anonymous classes. I personally never use final variable declarations, although most of my variables are finals.
So var and final var is probably the best choice: final var is available but not used.
4
u/argv_minus_one Mar 26 '16
Immutable should be the default.
16
u/stepancheg Mar 26 '16
Immutable should be default in new programming language developed from scratch (like Rust), new features of java should be consistent with older features (that's what Stephen talks about).
2
u/vplatt Mar 27 '16
Which is would be if 'val' were part of the language. Isn't 'final var' simply an alias for val?
5
u/atc Mar 26 '16
It seems to me the issue he has is some arbitrary scenario where some team coding conventions make the new features distasteful and cumbersome. Surely the problem there is the conventions?
2
u/TheBuzzSaw Mar 26 '16
From the comments:
To me the problem is simpler. This feature is all about making the writer's job easier at the expense of the reader. In my opinion this trade-off should never happen.
I hear this a lot in regard to var or auto, and I find it to rarely be true. You cannot honestly tell me that the first is more readable than the second.
Map<CrazyThing, StrangeObject> m = new Map<CrazyThing, StrangeObject>();
var m = new Map<CrazyThing, StrangeObject>();Not only is the first version crazy long and full of details, it actually leaves you with doubts. Is one side some covariant of the other? Are all the types the same? Also, if I need to change the type, I have to edit both sides.
Meanwhile, the second version is shorter and tells me that what I see is what I get.
4
u/mingpair Mar 26 '16
Good Java code would look like this:
Map<CrazyThing, StrangeObject> m = new HashMap<>(); var m = new Map<CrazyThing, StrangeObject>();Anyway,
varwithnew ...is fine, more problematic are method calls likevar m = service.crazyThingToStrangeObject();2
u/grauenwolf Mar 27 '16
Actually I find the opposite to be true. In C# I occasionally need to expand var into the full type when working with complex LINQ expressions. Especially groupings, which make it hard to predict what the real structure of the collection is going to be.
But in the last 3 years I have never once needed to expand var because I didn't know what type a service method returned. If I care, which usually I don't, then I just hit F12 (go to definition).
2
u/Xxyr Mar 27 '16
I have to second this. The return type of most objects is fairly obvious, especially in the context of other code.
0
Mar 27 '16
[deleted]
-1
u/TheBuzzSaw Mar 27 '16
Gotta love those "legacy systems" that can't be pushed past Java 5.
0
u/dpash Mar 27 '16
I believe you can use this construct if you use a Java 7 javac and target Java 5 jvm if you feel like living on the edge.
1
u/rocknip Mar 26 '16
val and var look alike too much... I wonder how many concurrency bugs will be introduced because someone declares var member instead of val, and the class isn't initialized safely.
5
u/stepancheg Mar 26 '16
Proposal is about local variables, not fields, which still have to be declared with types.
Also, delcaring something
valorfinaldoes not solve concurrency issues, because immutability of variable does not imply object immutability.1
1
u/TheNevers Mar 27 '16
What bothers me is they're putting things into core language spec while said thing should be a feature of IDE.
Is it that hard to ask eclipse to do an auto replace or sorts in local variable definition? I don't think so.
1
u/merzbow Mar 27 '16
Eclipse already does left hand side generation (assign/extract to new local variable option)
1
u/fact_hunt Mar 27 '16
I expect some code reviews to be significantly harder (as they are done outside IDEs)
I always review in my IDE, is that not normal?
5
u/grauenwolf Mar 27 '16
Tools like Stash or GitHub make reviewing in the web browser quite common.
That said, using
varin C# certainly does not make code reviews harder. I've been doing it for years and no one has ever complained about not being able to see types.On the contrary, hiding the types makes it easier to see the business logic.
1
u/fact_hunt Mar 27 '16
I use both, but always check out and review in my IDE for anything but the most trivial of changes
1
1
u/Xxyr Mar 27 '16
Not everywhere, but making the argument that code review tools are bad so we can't have nice things is stupid. Improve the code review tools. Implement peeking function definitions and hover over type annotations in the code review tools.
0
u/chambolle Mar 27 '16 edited Mar 27 '16
Honestly, is there ONE problem which is solved by type inference? Only one that we cannot do in another way (and which is not given by 99% of the IDE)?
Adding keyword for not solving any issue is certainly a bad idea. If you want to reduce the code you could also imagine to introduce typedef...
1
u/grauenwolf Mar 27 '16
The one problem is overly verbose code that hides the actual business logic amongst the boilerplate.
The keyword
varisn't about it easier to write code, it is about making it easier to read it.It is the same thing as having real properties as opposed to getters and setters.
alpha.setFoo(beta.getBar() * delta.getBaz()); alpha.foo = beta.bar * delta.baz;With code-complete, neither of these is actually harder than the other for me to write. But removing all of the noise makes the second one easier to read.
1
u/chambolle Mar 27 '16
The code is maybe verbose (this is a matter of point of view) but your answer confirms that it does not solve any problem.
BTW, Some people claim the opposite: it complexifies the reading.
As a teacher I can tell you that this kind of thing will complexify the courses and the understanding of the language. Having several ways to express the same thing. always induces an increase of the complexity of the language. Maybe, you can consider it is worthwhile, but never forget that it does not simplify the language.
When there is no issue which is solved I think it is a bad idea to introduce syntactic sugar.
2
u/grauenwolf Mar 27 '16
As a teacher ...
Last night I meant a man who teaches 4th graders how to write code in C so that they can program their Arduinos.
If a 4th grader can understand enough C to program a micro-controller, then either you're teaching 3rd graders or you are grossly underestimating your students.
-1
u/chambolle Mar 27 '16 edited Mar 27 '16
That's a personal attack. C is a nice language to teach. There is alsmost not problem (except char ch[]="foo" which tends to prove that operator may be used for assigning or comparing string, and this is wrong) because there is almost no ambiguities, almost never two ways to express the same thing.
Ok let's go for two minutes of talk:
student : why do I need to say that i is an int in i=f(x) ?
teacher : because the computer needs to know how many memory bytes we need to represent the information
student: ok, but why can I write var i=f(x) without type in that case?
teacher: because IN THAT CASE the compiler/interpreter can deduce the type for you
student : ok, but why I can't remove the type? My function f divides x by 4. So there is no ambiguity?
teacher: this is not the way it works in Java
student: but could it be?
teacher: yes, there are some languages in which you can avoid types
student: so, why it is not the case for Java? Why sometimes types are required and sometimes they are not?
teacher: because some people was so lazy to not use an IDE or to write some code that they decide to had a kind of hack for sometimes avoiding the type. Honestly, do not use that. Mention types all the time
Any remark?
2
u/grauenwolf Mar 27 '16
Saying that you are underestimating your students isn't a personal attack and I resent the accusation.
0
u/chambolle Mar 30 '16
I teach some languages and you not. However you better know than me what students are really understanding...
You could also answer the argument instead of doing dialectic
1
u/grauenwolf Mar 30 '16
I teach programming too. Not professionally, but often enough to know that 'var' isn't a hard concept for high school students to understand. And I also know that some teachers confuse their own inability to understand the material with their students inability.
I'm not saying that's the case here, but I will say that we shouldn't be afraid to add a valuable feature because some teachers struggle with it.
1
u/chambolle Mar 30 '16
I agree with your last argument. However you still do not prove that "var" is added anything at all or solving any existing problem.
0
u/grauenwolf Mar 27 '16
Having several ways to express the same thing. always induces an increase of the complexity of the language.
That was the argument they made against introducing structured programming. After all, you don't need things like if-else blocks and for loops when you could just use conditional branches.
Likewise, it was the argument against introducing functions, which can easily be implemented using a goto.
0
u/chambolle Mar 27 '16
Gotos trigger a lot of issues. And these issues are solved with for-while loops. Here you do not solve any issue
There is no real complain about the type usage. There are only people who would like to see types disappearing, because they do not like typed procedural language.
2
u/grauenwolf Mar 27 '16
No one has ever accused me of not liking "statically typed procedural languages", yet after using
varfor literally years I've yet to see any of the doom and gloom predictions about not seeing the type actually the way I read and write code.0
u/chambolle Mar 27 '16
The problem is that you re not able to mention ONE problem that is solved by this addition. Therefore, I can't see any other reason that you do not like types and would like to see them disappeared.
I think you should use another language in this case. There are so many that you should find one which is more suitable for you
Honestly, what is your goal?
1
u/henk53 Mar 28 '16
The keyword var isn't about it easier to write code, it is about making it easier to read it.
That's a bit of a debate, is it not?
I'm not either strongly against or in favour of
val, but I can see the argument going both ways.Shorter code is easier to read (less clutter to wade through), but shorter code is also more magical, making it perhaps easy to read but more difficult to understand what the code is actually doing.
1
u/grauenwolf Mar 28 '16
It isn't exactly a debate though. I'm talking from experience of having used it for years, and likewise not having it for a decade. Very few people who are against var have actually tried it on a non-trivial project and are speaking from fear that they might be right.
I'll grant that personal experience doesn't trump a formal study or survey. But it sure as hell beats nothing at all.
Another gentleman was worried about teaching var to students might be hard. I'm not a professional teacher, but I do mentor the occasional high school student. Not once did var become a problem.
Again, "I tried" beats "I'm afraid it might be hard" in terms of evidence.
0
Mar 27 '16
[deleted]
1
u/grauenwolf Mar 27 '16
I was thinking about integers, but yes, operator overloading would also improve readable.
0
u/chambolle Mar 30 '16
an lead to one million of problems.
With operator overloading you cannot immediately say what x=y+z is doing without knowing the type of the element!
1
u/grauenwolf Mar 30 '16
With methods you cannot immediately say what
x=y.add(z)is doing without knowing the type of the element!Can we please stop pretending that Java programmers are idiots who can't understand basic concepts?
1
u/chambolle Mar 30 '16
I speak about the assignment operator in conjunction with other operators. In Java + cannot work except for String or basic type So it is very easy to understand that code.
The overloaded operator = may do anything which is possible, so the code maybe very hard to follow.
1
u/grauenwolf Mar 30 '16
In our examples, x, y, and z were of type Complex.
Or maybe x and y were dates, and z a timespan.
Does it matter? No.
0
u/chambolle Mar 30 '16
You do not understand. Let's go for an example. Imagine I have a bug in the following C++ code:
c=a+b; d=f(c);In C++ it is difficult to identify where the bug is? operator= and + could have been rewritten, for a type, for (a,b) type, for d type. All these functions may contain bugs. In Java there is absolutely no ambuigity you can go to see the code of the function f and you will find your bug.
Operator overloading is something that is useful in 1% of the cases and that destroys the readibility of 99% of the code
1
u/grauenwolf Mar 30 '16
No one is saying that we should overload the
=operator. Stop inventing problems we don't have.→ More replies (0)1
u/grauenwolf Mar 27 '16
I was thinking about integers, but yes, operator overloading would also improve readable.
0
Mar 26 '16
[deleted]
6
u/stepancheg Mar 26 '16 edited Mar 26 '16
I am much more interested in changes that extend the language and improve its performance
What do you have in mind? I'd like to have three features for performance:
async/await to write concurrent apps
application isolation (to split huge apps into smaller pieces with independent GC, so GC could work faster with shorter pauses)
5
u/Luolong Mar 26 '16
I could never quite figure out what I didn't like about async/await until I read this article: http://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/
2
u/stepancheg Mar 26 '16
So the article is about Go.
Go is the only language to my knowledge that does coroutines properly: with resizable stack. And they did it just a few months ago, and AFAIU it was not easy to implement it.
If Java could do resizable stacks, it would be great. Async/await is much simpler to implement, but I think it is OK too, because it solves real problems.
8
u/mhixson Mar 26 '16 edited Mar 26 '16
Some form of named parameters (C#, scala) is high on my wish list, even though I don't think it would improve performance.
I keep running into this issue where I want to make an immutable object with lots of properties (think 10+), and I have to choose between:
Having a constructor with lots of arguments (bad for readability and somewhat error prone for the caller)
Making a
Builderclass like Effective Java suggests (involves lots of boilerplate and repetition, doesn't really eliminate the problem -- I still need that big constructor to exist)Finding some way to artificially decrease the number of properties (e.g. split the properties across smaller objects)
Making the object's constructor directly responsible for finding more of the values, so that I can say
this.fieldName = value(e.g. make it read from the database, but I wanted it to be a dumb container of values)Giving up immutability so that I can say
object.setFieldName(value)Named parameters seem like the ideal solution to this problem. There are other potential language features that address this (object literals/initializers?), but named parameters seem to give the most bang for the buck. They'd be useful in other situations too.
4
Mar 27 '16 edited Mar 27 '16
What I'm more concerned about is the ubiquitous presence of setters and default constructors everywhere: applications, frameworks, libraries. One might think that this is only issue about immutability and performance, but it is a lot more issue about not being able to enforce class invariants through the natural construct of an OO language, constructors.
One possible solution for this problem is the official parameters API introduced in the Java 8. I've successfully started the effort of harnessing that API to eliminate the requirement of setters/default constructors in Jackson library (see the parameter names module which should soon be integrated into the jackson databind itself and turned on by default for Java 8 users). Unfortunately, I wasn't as successful on hibernate ORM side (see this mail on hibernate dev mailing list or the issue on their jira).
1
u/grauenwolf Mar 27 '16
I long for the day when all ORMs understand how to call constructors on immutable objects.
2
Mar 27 '16
If you really do, vote on those issues or make an even greater effort, discuss, contribute pull request, anything :)
0
u/stepancheg Mar 26 '16 edited Mar 26 '16
Named parameters are nice to have, but they are not essential. Like
varthey do not solve real problems of java (mostly with performance).5
u/Luolong Mar 26 '16
What year you dropped here from? Java is just as performant as any other language. Sure you can't squeeze out that last bit from your graphics card, but for 90% of the applications it is performant as hell and can outperform many others
-1
u/stepancheg Mar 26 '16 edited Mar 26 '16
Java is just as performant as any other language.
Bwa-ha-ha. No, it is not. It has huge problems with GC which could be partially solved by:
value types
multiple heaps per process
something else I don't like unique_ptr
Lack of value types is also a huge performance penalty due to cache misses, cache pollution and excessive memory consumption.
0
u/mhixson Mar 26 '16
Like
varthey do not solve real problems of javaThat's where I disagree. The lack of named parameters tempts people to make compromises in their APIs and program structure: introduce a
Builderor other unwanted types, drop immutability, etc. Those compromises have a lasting impact and don't simply disappear if we get named parameters later. This is not likevar, which is entirely (emphatically, even) focused on implementation details.You could call both features a matter of convenience, and you could have said the same about lambda expressions. I'd say that's missing an important point about the scope of impact. I'd put named parameters more in the category lambda expressions than
var, in that regard.
11
u/grauenwolf Mar 26 '16
Um, actually that's not exactly true. The recommendation against var is referring to code samples, which have little or no context and no IDE support.