r/programming • • Mar 09 '16

var keyword proposed for Java

http://openjdk.java.net/jeps/286
250 Upvotes

395 comments sorted by

88

u/omair-majid Mar 09 '16

They are holding a survey on keywords (var, var/val, var/let): https://www.surveymonkey.com/r/KGPTHCG

Bikeshed away!

40

u/oscarreyes Mar 09 '16

I would love to see var / final

var   a = expr; 
final b = 1;

31

u/sudowork Mar 10 '16

Var/val from Scala is pretty reasonable as well.

16

u/kcuf Mar 10 '16

And already used by JVM developers that mix languages (I believe Kotlin uses this as well as Scala).

1

u/vorg Mar 10 '16

As also does Apache Groovy, though it calls it "def".

11

u/FrozenCow Mar 10 '16

Not a big pro, but it also aligns nicely.

7

u/kukiric Mar 10 '16

Though the one-character difference between the two keywords might cause some confusion about whether a local is final or not, and it would break existing code that uses any variables named "val" (as undescriptive as it is, it's still pretty common). "var/let" would be more reasonable for these reasons, IMO.

7

u/orclev Mar 10 '16

That's why I voted for var/let, I like that they're easier to tell apart. I feel like var/val would be just a bit too easy to typo.

→ More replies (5)

6

u/mirhagk Mar 10 '16

it would break existing code that uses any variables named "val"

Would it? Are all keywords in java reserved and unusable as variable names? (var would be problematic too as well). When C# introduced var there was no compatibility issues as var wasn't valid anywhere where variable names were valid, and if a type in scope happened to be named var (which would go against the naming conventions anyways) that type would simply be used instead of the keyword. In C# the following program compiles perfectly fine before and after the introduction of var

void Main()
{
	var var = new var();
	var.num = 4;
}

// Define other methods and classes here
class var
{
	public int num{get;set;}
}

and using int var = 5; is likewise perfectly fine. If you don't have a var type then var var = "var"; creates a variable named var that is type inferred as a string. I don't know if the Java team wants to create this context sensitive complex grammar, but if they are willing to then it can be completely backwards compatible.

3

u/gbear605 Mar 10 '16

Just checked with Java keyword usability as variable names.

If I do

int int = 5;

it errors with

[javac] file.java:67: error: not a statement

[javac] 			int int = 5;

[javac] 			^

[javac] file.java:67: error: ';' expected

[javac] 			int int = 5;

[javac] 			   ^

[javac] file.java:67: error: not a statement

[javac] 			int int = 5;

[javac] 			    ^

[javac] file.java:67: error: ';' expected

[javac] 			int int = 5;
→ More replies (1)

1

u/[deleted] Mar 10 '16 edited Mar 10 '16

You can also use the val part in Java today with https://projectlombok.org/features/val.html. Works great.

19

u/danneu Mar 09 '16

really the immutable reference should be the shortest one to type so that it's default. too late for java, of course. this is something i think rust got right. let vs mut let.

javascript fucked it up too. let vs const.

8

u/Ununoctium117 Mar 10 '16

It's let mut, not mut let fyi :D

→ More replies (9)

4

u/irarandomdude Mar 10 '16

Just use var for non-final and val for final like everyone else does.

1

u/mirhagk Mar 10 '16

some people use let. var/val is common but certainly not the only way.

2

u/plastikmissile Mar 09 '16

Is "final" declaring an immutable?

11

u/TheNiXXeD Mar 09 '16

Final already exists. It's not about immutability, but you can't reassign that reference.

16

u/rabidcow Mar 09 '16

It is about immutability, but shallow immutability. Since primitives are the only values types, that means just the reference for anything else.

2

u/id2bi Mar 10 '16

Or say that we are talking about the (im)mutability of variables, not values.

I'm not sure talking about "shallow immutability" is appropriate in this context. When you do a shallow copy, only the fields will be copied (i.e. copies of primitives, and copies of references), so this suggests that shallow immutability means the fields will also not be re-assignable.

This is also backed up by this:

https://homes.cs.washington.edu/~mernst/pubs/immutability-aliasing-2013-lncs7850.pdf

→ More replies (1)

2

u/yoden Mar 10 '16

This is better than any of the options in the survey.

0

u/[deleted] Mar 09 '16

[deleted]

11

u/immibis Mar 10 '16

The parser would become slightly more complicated to deal with cases like

final String = 5;
             ^ apparent parse error?

(In Java it is legal to have a variable with the same name as a type)

1

u/weltraumaffe Mar 10 '16

So wouldn't you just have an int with the value 5 named String? I don't see the problem.

5

u/kqr Mar 10 '16

But to figure that out you need to backtrack, which they presumably want to avoid in their parser.

3

u/immibis Mar 10 '16

You don't know whether String is supposed to be a type or a variable until after you read the next token, because this is also valid:

final String x = "hello";
→ More replies (1)

0

u/[deleted] Mar 10 '16

[deleted]

→ More replies (1)

8

u/Jacoby6000 Mar 10 '16

Why not var for mutable things, and Val for immutable things?

3

u/ComradeGibbon Mar 10 '16

That's pretty nice actually. val/Val/value is immutable. var is mutable.

value quarter_pi = 3.14/4.0;
var foo = bar->baz->foo;
foo += quarter_pi;
→ More replies (8)

18

u/[deleted] Mar 09 '16

[removed] — view removed comment

15

u/RobIII Mar 10 '16

I wish C# have final or something equivalent for local variables.

Watch this one: Proposal: 'readonly' for Locals and Parameters

→ More replies (3)
→ More replies (8)

-2

u/immibis Mar 10 '16

puts on beginner-coloured glasses

It seems like auto would make the most sense (you can replace a type with auto and the compiler will automatically fill in the type), followed by var (because you're declaring a variable).

var/val would be easily confused, and let is based on abstract mathematical stuff (and therefore unintuitive unless you've studied abstract mathematical stuff).

→ More replies (1)

83

u/the_evergrowing_fool Mar 09 '16

We seek to improve the developer experience by reducing the ceremony associated with writing Java code

So, they are aware and it seems to dismiss the myth that Java was designed as a pseudo language to summon Cthulhu.

47

u/setuid_w00t Mar 10 '16

You can't summon Cthulu directly. You need to unmarshal one from the CthuluXmlFactory instance.

9

u/mlk Mar 10 '16

Have to pass the NecronomiconInputStream though

5

u/[deleted] Mar 10 '16

What if I have the Necronomicon in a byte input stream but I don't know the size of the stream in runtime?

37

u/bargle0 Mar 09 '16

Nah, that's Perl.

25

u/JoshWithaQ Mar 10 '16

you must not be a perl programmer.

Cthulhu is a puppy dog compared to what Perl summons.

6

u/bargle0 Mar 10 '16

I am, actually.

use summon qw(Thamagorgos);

8

u/mpyne Mar 10 '16

Certainly there's not much 'ceremony' to Perl. It would almost be easier to use if there were more ceremony.

1

u/mirhagk Mar 10 '16

Now Java just needs to get properties to reduce the amount of code by 90%.

56

u/[deleted] Mar 10 '16

[removed] — view removed comment

33

u/ksion Mar 10 '16

Or just Vogons.

30

u/EveningNewbs Mar 10 '16

So Oracle?

72

u/htuhola Mar 10 '16

Knowing java, this proposition will win:

var List<String> list = new List<String>();

19

u/__konrad Mar 10 '16

I propose autovariable list = new List<String>(); ;)

15

u/stun Mar 10 '16 edited Mar 14 '16

More like this. You need this before you have your cute little snippet of code.

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.site.myjawdroppingsuperverboseconfigbasedapplication</groupId>
  <artifactId>i-love-my-super-verbose-xml-config-files</artifactId>
  <version>1</version>
  <dependencies>
    <dependency>
        <groupId>com.another.group</groupId>
        <artifactId>we-are-reinventing-the-wheel-ibrary</artifactId>
        <version>8.3.1</version>
        <scope>app</scope>
    </dependency>
  </dependencies>
</project>

33

u/FallingIdiot Mar 10 '16

Funny that when this subject comes up, almost everyone only talks about it making local variable declarations simpler.

What I think is a big advantage to var is that when you change the name of a class, it significantly reduces the number of files that have to be changed. Basically everything that doesn't instantiate the class, but only uses it, stays unchanged. Also it keeps down the number of imports you need, especially since Java prefers fully qualified imports instead of wildcard imports.

30

u/Roozi Mar 10 '16

While I agree that it helps, in my experience IDEs are usually pretty good at doing this for you.

22

u/[deleted] Mar 10 '16

That's true, but also the changes clutter up diffs and code reviews.

8

u/JW_00000 Mar 10 '16

And may also lead to merge conflicts with unrelated changes in those files.

5

u/ygra Mar 10 '16

Oh yes, the merge conflicts. At work we have a large-ish codebase that gets merged into different products and also converted into different languages. One of the worst things regarding merge conflicts are renames.

12

u/RupertMaddenAbbott Mar 10 '16

This advantage is not about making it physically easier to rename a class. It lessens the impact of doing so, therefore making it easier.

It reduces the number of files that might change when you do rename a class. This could significantly reduce code churn and removes noise from files that do change.

→ More replies (1)

11

u/G_Morgan Mar 10 '16

It really depends. A lot of C# projects have a rule to only use var where there is a straight up class instantiation or cast. The idea is to have at least some type definition somewhere near the declaration.

The purpose of var is to stop bullshit like "X<Y> foo = new X<Y>();"

7

u/Eirenarch Mar 10 '16

I came up with this rule by myself and found out that many people came to the same conclusion. I only use var when the right hand side expression is either a constructor call or a literal. Basically the type should be obvious by the statement.

var customers = GetCustomers()

is not a good idea in my opinion

7

u/Ravek Mar 10 '16

IEnumerable<Customer> customers = GetCustomers(); doesn't tell you a single thing you need to know that var didn't already.

14

u/Eirenarch Mar 10 '16

Oh yes, it does tell me. It tells me I have an IEnumerable<Customer> rather than IEnumerable<CustomerDto> or PagedList<Customer> or something like this.

2

u/Ravek Mar 11 '16

That should already be obvious from context.

→ More replies (3)
→ More replies (17)

3

u/BezierPatch Mar 10 '16

IEnumerable vs IQueryable vs IList is pretty good to know.

2

u/mirhagk Mar 10 '16

That should be fairly obvious from context. If your code base believes in passing IQueryable in your DAL back to consumers then you should know that db.GetCustomers() is IQueryable<Customer>.

3

u/id2bi Mar 10 '16

Can't we already do that due to the diamond operator? Usually the Y is the cumbersome part.

X<Y> foo = new X<>();

2

u/[deleted] Mar 10 '16

Yes. It mostly improves readability a lot.

2

u/cat_in_the_wall Mar 10 '16

Or even changing the return type of a function. Let's say that someone subdivides an interface into a "lower" interface, and a more specialized one. Using var allows for the places in that only care about that lower interface to continue to work. Sure some stuff needs to be changed, but the change can be smaller.

1

u/ledasll Mar 10 '16

if you change return type or argument type you definitely want to look, who is using it and having clear type here helps a lot. For library programmers, that's of course nothing. But for application programmers..

1

u/mindbridgeweb Mar 10 '16 edited Mar 10 '16

This proposal makes writing code without an IDE simpler and reading foreign code potentially much harder.

Consider the following code:

URL serverUrl = ...;
var serverConn = serverUrl.openConnection();
var props = serverConn.getRequestProperties();

Can a developer determine the type of the 'props' variable above right off the bat?

Really, it will definitely take a while to answer this simple question. If this code was written in the current Java style, however, we would have known the type right away.

And this is only for a couple of lines of code. This effect will be horrible in larger programs -- they will be effectively much harder to understand by humans without IDE assistance.

In short, this proposal only simplifies writing code without an IDE (is anyone still doing that?). The problem it fixes is negligible when using an IDE -- you can just press Alt-Shift-L in Eclipse for example.

On the other hand the proposal greatly complicates code comprehension when not using an IDE and slows it down even with an IDE. And there is a HUGE number of cases where developers need to read code without an IDE, e.g. viewing code on github, doing code reviews based on diffs (like reviewboard), printed code examples, online code presentations, etc, etc.

We are solving a small problem and creating a huge new one.

17

u/_INTER_ Mar 09 '16

How will this deal with code like:

List<String> lst = new ArrayList<>();    

I always wondered why they've choosen to abbreviate the RHS instead of the LHS (in Java 7 I think). Clear me up please.

9

u/codebje Mar 09 '16

The proposal has an example for just such a case:

var lst = new ArrayList<String>();

The inferred type will not be List<String>, it'll be ArrayList<String>, but thanks to polymorphism you can use that anywhere you'd want to use a List<String> anyway.

2

u/_INTER_ Mar 09 '16

I was more thinking about how it will invere

var list = new ArrayList<>();    

14

u/bjzaba Mar 09 '16

That would require a smarter type reconstruction algorithm, like Hindley-Milner. That's probably a step too far for the conservative Java committee.

3

u/Sean1708 Mar 10 '16

The day Java gets HM is the day I walk around town with "The End Is Nigh" hanging around my neck.

2

u/csman11 Mar 10 '16

I remember seeing an SPJ talk where he mentioned that HM cannot be used in OO languages because of subtyping (he didn't explain this). But that obviously will never happen in Java. Someone correct me if I'm wrong. I don't know a lot about type inference.

The video was something like "classes but not as you know them" on channel 9 and was about type classes. The above was briefly mentioned in the last few minutes.

Edit: title was "classes, jim, but not as we know them"

→ More replies (2)

4

u/codebje Mar 09 '16

If it was using full type inference, it'd examine the use sites of list to infer what the contained type should be.

But I think that the scope of this proposal doesn't go so far, and that would be an error.

3

u/im-a-koala Mar 10 '16

I'm not convinced that's even a good idea in the first place, honestly. I would be rather confusing to have the type of a local inferred by future uses of the local.

2

u/codebje Mar 10 '16

It would be something like this:

public List<String> greet() {
    var list = new ArrayList<>();

    list.add("Hello, ");
    list.add("World");
    return list;
}

Let's just look at the expression return list here. Its abstract syntax tree will be a Return node with list as the expression to return, and the type of the return expression must be assignable to List<String>. Whatever type list has, it must now satisfy assignability to List<String> for the types to unify.

If we also look at var list = new ArrayList<>();, we know the right-hand side of the expression has a type of ArrayList<a> where a is an unresolved type, and thus the left-hand side must be of a type which is assignable from ArrayList<a>.

At this point the compiler can reconcile that List<String> must be assignable from ArrayList<a>; a List is assignable from an ArrayList, so that's fine, but the only thing which a can be for this to compile now is String: the signature for List<String> is not variant in its generic type.

A type inferencing algorithm has some choice here: it can work out the most general type which suits, or the most specific type, or any type which satisfies all known conditions. AFAIK most algorithms go for the most general type, and narrow it as needed, so let's go for that.

What's the most general type which can be assignable to both a List<String> and an ArrayList<String> ? Well, it's just List<String>, so therefore the type of list should be List<String>.

We check that against the remainder of the AST, notably the expressions list.add("Hello, ") and list.add("World"). These require a method add(=String) on list, using made-up syntax to express that the method needs an argument type assignable from String. This checks fine, as String is assignable from String in the signature add(E ...) where E is String.

All that magic happens under the hood, but when you read that, it's pretty obvious that the type of list must be something which can hold an ArrayList, and the ArrayList's generic argument must be String, because you've gotta be able to assign the ArrayList in, add some Strings to it, and return it as a List<String>.

It's my opinion that the code above has all the information a programmer needs to understand what's going on. Whether list is typed as List<String> or ArrayList<String> doesn't really matter, because (a) the object it refers to is definitely going to be an ArrayList<String> no matter the variable's type, and (b) it'll be returned as a List<String> no matter the variable's type. There's no ambiguity in the meaning of the code, and some boilerplate declaration of "obvious" types is removed.

Static typing really shines when it gives you all the compile-time guarantees of correctness that a static type system allows, yet doesn't require wads of tedious boilerplate when it's "obvious by looking at it".

Being freed from worrying about intermediate types is already a great win for Java 8's expressivity, a similar freedom from worrying about the type of transient variables is something I welcome :-)

3

u/normalOrder Mar 10 '16

This is a great explanation, but it also demonstrates a huge reason why it won't happen: the Java designers assume most Java programmers are too dumb to understand.

some users imagine type inference to be a form of mind reading, rather than an algorithm for constraint solving

4

u/im-a-koala Mar 10 '16

Yeah, and I think that example is awful. Okay, it looks cute for a very small, unrealistic function with a single local and only adding literals, but once you get 20-30 lines, throw in more than one local, and add things to the list that are returned from other functions, it quickly becomes very, very difficult to reason about.

6

u/Sean1708 Mar 10 '16

I dunno, it's working out pretty well in Rust.

→ More replies (1)
→ More replies (1)
→ More replies (1)

2

u/Eirenarch Mar 10 '16

This won't compile. You will use

var list = new ArrayList<String>();

instead. There is no benefit from the diamond syntax in the presence of var.

0

u/immibis Mar 10 '16
var lst = new ArrayList<String>();
lst = new LinkedList<String>(); // oops!

5

u/Oniisanyuresobaka Mar 10 '16

I don't know why you would even want to do that except to confuse future maintainers by reusing a variable when you clearly need it for a different purpose and even if your code was perfectly acceptable it would require full type inference, otherwise it wouldn't be possible to find the common super type for all assignments.

1

u/immibis Mar 10 '16

More likely:

var lst = new ArrayList<String>();
if(condition)
    lst = someMethodThatReturnsAList();
→ More replies (1)

1

u/codebje Mar 10 '16

Good argument for full HM type inference, that :-)

8

u/henk53 Mar 09 '16

I always thought that it was simply an extension of the earlier limited type inference that already existed for generic methods (since Java 5).

In the generic method case you do:

List<String> lst = someObject.someMethod();

Since someMethod is defined generically there's nothing to abbreviate here at the RHS. The method is just a generic method with <T> in front of it returning a List<T>.

You could see the constructor as a special method, so in pseudo code if you changed it to:

List<String> lst = new ArrayList.ArrayList();

It may become clear why the RHS was abbreviated. Additionally, it's only because of legacy and the concept of raw type that we were never able to write:

List<String> lst = new ArrayList();

Since that syntax was already taken and retrofitted for the introduction of raw types, instead of "simply" be upgraded (like methods were) to have limited generic type shortening.

7

u/s888marks Mar 09 '16
List<String> lst = someObject.someMethod();

Assuming that someMethod is generic, this really is an abbreviation for

List<String> lst = someObject.<String>someMethod();

The type inference for generic methods works so well that this syntax is rarely necessary, so rare that many people don't even know this syntax exists.

1

u/henk53 Mar 09 '16

True, although I've needed to use it on a couple of occasions though. In a select few cases because of a compiler bug where the type should have been inferred but wasn't.

1

u/im-a-koala Mar 10 '16

It comes before the method name in Java? Huh. In C# it comes after, like:

List<String> lst = someObject.someMethod<String>();

5

u/immibis Mar 10 '16

Probably chosen because that's harder to parse, because the compiler doesn't know whether String is supposed to be a type or a variable until it gets to the >.

(Consider:

class X {
    int getValue;
    <T> int getValue() {return 5;}
}
X someObject = new X();
int String = 7;
int i = someObject.getValue<String?1:0;
int j = someObject.getValue<String>();
//                                ^

and don't complain about the bad naming, because that is legal in Java)

1

u/kcuf Mar 10 '16

That's what Scala does as well

List[String] list = someObject.someMethodString

or, more commonly seen as

List[String] list = someObject.someMethod[String]

→ More replies (2)

1

u/irarandomdude Mar 10 '16

It won't, and doesn't need to. It's the same in Scala, you'd have val lst: Seq[String] = ArrayBufferString

1

u/[deleted] Mar 10 '16

val lst: List<String> = new ArrayList()

;)

→ More replies (13)

17

u/IronClan Mar 10 '16

This was linked to ##java a few hours ago and people were absolutely pissed off about it. It seems many members of the Java community see this as a sign of programmer laziness, and there are even others who think type deduction == dynamic typing.

13

u/irarandomdude Mar 10 '16

This is what happens when the Java community drinks their own kool aid. It follows the usual pattern:

  1. Claim that Java doesn't have feature X because it is evil.

  2. Feature X gets added to Java.

  3. Claim that the addition of feature X is evidence of Java being modern and current and how it makes Java just as expressive as language Y.

5

u/[deleted] Mar 10 '16

When is ##java not pissed about things? I have never seen a chat channel so filled with angry and unpleasant people

→ More replies (2)

9

u/yoden Mar 10 '16

I do see it as a minimal reduction of typing for a nontrivial reduction in readability.

5

u/[deleted] Mar 10 '16

Having pointless noise all over the code (duplicated type information) is an increase in readability ? Welcome to the mind of PointlesslyTediousToThePointOfInsanityJavaDeveloperFactory

5

u/jrh3k5 Mar 10 '16

When working in Groovy, I always found declarations like this maddening:

def result = extractor.getResult()

The IDE wasn't able to figure out, necessarily, what type of object "result" was, so I'd not get the benefit of Eclipse's built-in tooling that leverages explicit type declaration (e.g., suggestion of possible methods). It also made reading the code outside of an IDE (e.g., GitHub) more difficult, especially if I didn't know the type of object(s) returned by "getResult()". That's one of the things I really disliked about Groovy and why I'm not entirely thrilled about adding a "var" keyword.

4

u/stormblooper Mar 10 '16

It's a feature that can give you a modest improvement in readability when used in the correct context, because it's less noisy.

1

u/yoden Mar 10 '16

But only sometimes, and only if it's used well.

Var makes good code easier to read, and bad code harder to read. So it helps a small amount in the case where you do not really need improvement, and creates problems in the cases where you do.

3

u/stormblooper Mar 10 '16 edited Mar 11 '16

Local type inference gives you the option to stop saying redundant things over and over again, the typical way Java makes you say the same thing in triplicate:

SomeInevitablyLongNamedThing<Integer> longNamedThing = new SomeInevitablyLongNamedThing<Integer>();

It's noise, and it makes both good and bad code harder to read.

In Scala, my rule of thumb is to ensure that 1) the variable name and 2) the RHS of the assignment, taken together, give a decent indication of the type of the variable, sufficient to understand the intention of the code. If that condition isn't met, I prefer to add explicit type annotation.

If you're worried about making bad code harder to read, my suggestion would be to replace the bad code with good code.

0

u/Carighan Mar 10 '16

Same here. I don't really see the gain, and it just means I have to hunt down types.

3

u/adamnew123456 Mar 10 '16

I thought Java people used IDEs for this. When's the last time you tried to read code that was actually used for something without firing up Eclipse et al. to do so?

For what it's worth, the Scala toolset for Eclipse will show you the inferred type of a value by hovering over it. There's no looking involved.

1

u/yoden Mar 10 '16

Every time I do code review. I wish there were good code review systems for IDEs.

8

u/brcolow Mar 09 '16

Does anyone know if this is going to be targeted at 9 or 10?

5

u/MrBIMC Mar 10 '16

9 is basically almost frozen already, especially for such a complex change.

4

u/cat_in_the_wall Mar 10 '16

Not trolling... why would this be complex? They already need to know the type of the right side of the expression, saying int x = 0.0 doesn't work, so they must already compare the lhs to the rhs. I would think that it would be fairly straight forward to defer the lhs type until after the rhs is known.

8

u/immibis Mar 10 '16

It's not complex to implement, but they'd have to consider all the weird cases, and write a section in the JLS for it, and probably check that other compilers can implement it reasonably, and check they're not shooting themself in the foot later.

It's also a new keyword.

(For an example of a weird case: x has what type here?

var x = () -> {System.out.println("foo");};

)

2

u/Tarmen Mar 10 '16

Been a while since I used java, why is that type ambiguous? Was it something like having to bind lambda expressions to an interface? Seems like inferring void=>void would be possible?

2

u/immibis Mar 10 '16

void=>void isn't a type in Java. It can be any interface that has a void=>void method - normally, which interface is deduced from the context you use it in (e.g. the type of the variable you assign it to).

2

u/_klg Mar 10 '16

In this case you would have to declare the type explicitly. This happens in C# as well, you can't assign an anonymous method to a var.

→ More replies (1)

5

u/otakuman Mar 10 '16

So, C++'s auto keyword?

2

u/upboatingftw Mar 10 '16

I wouldn't say they really compare. C++'s auto allows you to write declarations like auto const**const&, because it's based on template type inference semantics.

This proposal looks closer to what Scala provides.

4

u/NihilCredo Mar 10 '16

auto const**const&

nope.jpg

1

u/upboatingftw Mar 11 '16

But how else are you going to express that you want a reference to a constant pointer to a pointer to a constant inferred type (moving the first const in front aside)?

Jk, it was just a ridiculous example I gave to illustrate auto's workings. Such qualifications kinda defeat the purpose of auto, and there's no good reason to pass a constant pointer by reference either.

10

u/kirbyfan64sos Mar 09 '16

YESSSSSSSSSSSSSSSSSSSS!

14

u/lamarf Mar 09 '16

Statically, not much is going to change from this, so that's fine, but it's still going to hurt readability if you're assigning new variables from method returns that aren't immediately obvious. It's good and cool to know right away that this variable I'm looking at is going to be a String -- because it's been declared explicitly -- rather than the implicit case where you have to jump to the method signature to figure out what's being returned.

19

u/BinaryRockStar Mar 09 '16

In pretty much any IDE you can hover over a method call and it'll give you the signature, or hover over the variable and it'll give you the type.

10

u/lamarf Mar 09 '16

You're not always going to be looking at code through an IDE, though (i.e. if I'm looking at a code review on GitHib, which honestly makes up a lot of my time spent), and for large projects, the indexing that makes that happen can be painfully slow and sluggish to use (I'm looking at you, Eclipse). And either way, it's always going to be better for readability if the information I need is right there on the screen for you, not hidden behind clicks and interaction with the IDE.

5

u/tybit Mar 10 '16

Its a continuum of how much information is hidden without going to the implementation. A lot of the time knowing the type won't help that much anyway. So:

'CustomerValidationResponse response = CustomerValidator.Validate(customer);'

and

'var response = CustomerValidator.Validate(customer);'

are equally obscure without going to the definition if you aren't already familiar with the code. I find it to be the exception not the rule that the implicit declaration is what makes the code unclear.

3

u/yoden Mar 10 '16

In the var example, I have to know what CustomerValidator.Validate returns and what a CustomerValidationResponse is.

With the explicit type I only have to know what a CustomerValidationResponse is.

→ More replies (3)

4

u/FMAlfonse Mar 09 '16

I have been of the opinion in c++, that if the type isn't obvious then you shouldn't use auto. That doesn't mean auto isn't useful iterators are horrible to write, using auto it = myVector.begin(); makes it alot more pleasant to both read and write. However I would use std::string result = aClass->someFunc(); Best of both worlds but getting people to adhere to it can be a nightmare.

1

u/immibis Mar 10 '16

I have been of the opinion in c++, that if the type isn't obvious then you shouldn't use auto.

Unfortunately, the person whose code you're trying to read does not have that opinion.

6

u/kqr Mar 10 '16

"But you can use it to write bad code" is always the argument against introducing a language feature. It doesn't matter which feature. Someone will say it's a bad idea because you can write bad code with it.

Guess what? You can do that with any feature. It's a bad argument.

2

u/immibis Mar 10 '16

"It encourages bad code" is a reason against introducing a language feature. Even for things that are controversially bad (i.e. not everyone agrees they're bad).

See some of the other comments on this very post.

3

u/kqr Mar 10 '16

Sure, that's a better argument. I guess we disagree on the degree to which local type inference encourages bad code.

→ More replies (1)

2

u/stun Mar 10 '16

It seems that Java developers don't really understand why it is very useful.
Regardless of how much the IDE can help with intellisense/type, having this var is an amazing feature that simplifies the code clutter.

1

u/Carighan Mar 11 '16

By requiring me to hover over variables to find out their type?

1

u/stun Mar 14 '16 edited Mar 14 '16

By the time you scroll down, you don't know what type it is anyway.
You mouse-hover it to see its type at that point regardless.

If you can see the variable declaration, there is no need to mouse-hover.

Consider the following declarations.
Which do you think is easier to read/scan?

var dictPeople = new Dictionary<int, People>();  
var listPeople = new List<People>();
var peopleListByDept = new Dictionary<int, List<People>>();

vs

Dictionary<int, People> dictPeople = new Dictionary<int, People>();  
List<People> listPeople = new List<People>();  
Dictionary<int, List<People>> peopleListByDept = new Dictionary<int, List<People>>();

2

u/yturijea Mar 10 '16

I see that a lot of people like this "var" thing, but really you end up reducing the code quality. var a = something(); is just confusing and you'd have to lookup the method to see the type.

I did quite some c# and I first did var. After some time I changed it to the type it was supposed to be. Remember you have to be clear in your language. By declaring "var" you are confusing the next maintainer and or yourself.

1

u/silveryRain Mar 10 '16

I've only ever found it confusing in bad code, e.g. when something() returns a value of a type that is anything but what you'd expect something() to be.

7

u/yoden Mar 09 '16

I wonder what the benefit of this is supposed to be, other than other languages have it?

Explicit types on variables are useful for improving readability. Conciseness for LHS variable types isn't important because I usually don't write that type anyway (that's what an IDE's "assign to new local variable" is for)

7

u/[deleted] Mar 09 '16

C#s var was introduced to alleviate the burden on the developer to figure out the outcome of Linq queries.

1

u/yoden Mar 10 '16

Why? Does Visual Studio not have an equivalent to eclipse's "assign to new local variable"? It seems easier to write the LINQ query first and let the IDE handle the declaration.

1

u/Alikont Mar 10 '16
  1. Sometimes it's simply not possible, like if you use anonymous types.

  2. ILookup<string, IGrouping<int, Something>> v = GetSomething() is much uglier than var v = GetSomething().

→ More replies (1)

5

u/[deleted] Mar 10 '16

[removed] — view removed comment

1

u/wwosik Mar 10 '16

Do I remember correctly that in older VB or at least VBA

 dim list as new ClassName()

had a very nasty property of only creating object on the first access to it - lazy constructor of sorts

1

u/Cuddlefluff_Grim Mar 10 '16

Syntax error

DIM list AS ClassName
SET list = new ClassName

Notice the SET statement, because in old VB, normal variables and class variables were two entirely different things. Classes were implemented in order to properly support C++ COM interfaces. They were pretty much useless in any "custom" scenario.

17

u/jyper Mar 09 '16

Explicit typing is overrated and most of the time named of variable and expression on right hand side should give you enough information plus it reads better. There is a reason all modern statically typed languages are jumping on this train.

15

u/[deleted] Mar 09 '16

[removed] — view removed comment

5

u/kqr Mar 10 '16

For what it's worth, any report I've heard of "Haskell in the wild" have included both inexperienced team members and code that is easy to maintain. Haskell uses type inference a lot, so either Haskell is the odd one out that for some other unrelated reason makes it work, or type inference isn't actually as bad as you imagine.

1

u/Oniisanyuresobaka Mar 10 '16

From what I've seen generally it's considered good practice to write down the function signature even when it's not needed.

2

u/kqr Mar 10 '16

For top level functions, yes, because their scope is big. Not as common for local declarations.

7

u/Radixeo Mar 09 '16

It would help keep the line length down. In this common example

ArrayList<String> foo = new ArrayList<String>();
var foo = new ArrayList<String>();

The second line is shorter, simpler, and it is still obvious what the type of foo is.

19

u/depressiown Mar 09 '16 edited Mar 09 '16

ArrayList<String> foo = new ArrayList<String>();

You shouldn't be doing this since 1.7 and should be using the diamond. The real comparison here is:

List<String> foo = new ArrayList<>();
var foo = new ArrayList<String>();

Without the left side, you have to move the generic type to the right, whereas with the current notation you can use the diamond since Java can infer the generic type on the right side from the left side.

Honestly, I don't see a lot of gain here. Lombok has val, which is similar, but limited, though it would be better if it were inherent to the language. That said, I like things being explicit so I am biased.

1

u/four024490502 Mar 09 '16 edited Mar 09 '16

and should be using the diamond.

I haven't programmed in Java for a while. What's the diamond?

Edit: Oops... my initial google search for 'java diamond' turned up a bunch of 'Java introduction printing a diamond pattern' tutorials. This explains it. I think my original point below still stands, though.

Doesn't that only expose List<String> as the interface for foo? What if I want to manipulate foo with a method defined in ArrayList<String>, but not specified in the List<String> interface?

4

u/depressiown Mar 09 '16 edited Mar 09 '16

Ignore the fact that I used the interface instead of the implementation class on the left side. It's just good practice since you abstract the implementation class, but sometimes won't work if the implementation class has some implementation-specific method you need. Either way, not relevant when discussing the diamond.

The diamond (<>) can be used if Java can infer the generic type of the implementation class (the right side of the expression). This is "new" in Java 7. For example...

List<String> foo = new ArrayList<String>();

... is exactly the same as:

List<String> foo = new ArrayList<>();

Since Java 7, it can infer the generic type on the right side is String. However, if Java can't infer it, it won't compile. For example, this method will not compile:

public List<String> foo() {
    return new ArrayList<>();
}

There is no left side. Java can't infer the generic type of "new ArrayList<>()". In this case, you would need ArrayList<String>(). Hopefully that makes a bit more sense about the diamond. You can Google it if I'm not explaining it very well.

My larger point is that right now, the diamond allows Java to infer the generic type. If we use something like var, that inference is gone and now you have to define the generic type on the right side. While you gain not having to define any type on the left, you now lose the ability to shortcut the generic type on the right side. Overall, it's a positive gain for number of characters, but it's not as large as people make it out to be for objects with generics... and to some, there's a loss of readability by not having the explicit type on the left.

3

u/s888marks Mar 10 '16
public List<String> foo() {
    return new ArrayList<>();
}

This compiles and works fine in 7 and beyond. The left-hand side is the return type of the method.

→ More replies (3)

5

u/[deleted] Mar 09 '16

[removed] — view removed comment

6

u/depressiown Mar 09 '16

My point is that with val, Java won't be able to infer the generic type on the right side of the expression. You'll now have to define it, whereas you wouldn't with diamond, so long as the left side is explicit.

Using val will reduce the number of characters, but not by as much as you might think for objects with generics.

I'd argue that the diamond is not so narrow a use case as you might think, too, and that val hurts readability by making the left side non-explicit. Those are purely opinion, though.

→ More replies (2)

9

u/Helene00 Mar 10 '16

Another example:

var f = new SimpleBeanFactoryAwareAspectInstanceFactory();

instead of

SimpleBeanFactoryAwareAspectInstanceFactory f = new SimpleBeanFactoryAwareAspectInstanceFactory();

4

u/psxpaul Mar 09 '16

That example is clear, but even in the linked proposal, there are things like:

var stream = list.stream();

I'm guessing this could even lead further to:

var thing = foo.bar().processResults()

Where you have no idea what type 'thing' is just by looking at it.

8

u/codebje Mar 09 '16

True, but we do this already with lambdas. What type is the forst lambda in:

List<String> resultSummaries = list.stream()
    .map(a -> a.getResult())
    .map(r -> r.getSummaryLine())
    .collect(Collectors.toList());
return resultSummaries;

And more importantly, does it really matter given the compiler is statically checking your types anyway? If there's no type inferable (or it's ambiguous) there will be a compile error.

Compare with:

var results = list.stream().map(a -> a.getResult());
var summaries = results.map(r -> r.getSummaryLine());
var resultSummaries = summaries.collect(Collectors.toList());
return resultSummaries;

There's plenty of type inferencing going on in both cases. Explicitly calling out the type of the result, the type of the summary line, and the type of the list don't do a whole lot for improving understanding, IMO: it doesn't matter very much what type a result is, the intent is clear that we'll ask each result to produce its summary line, then collect those into a list.

→ More replies (1)

6

u/KagakuNinja Mar 09 '16

Coming from scala, val / var plus type inference is a godsend at reducing the visual clutter of code. Much of the time, we don't care what the exact type of "thing" is, we are going to pass it to another function, or return it.

The key with scala is that type annotations are optional. You use them when it is helpful for readability (or in some cases, to keep the type inference engine from getting confused, but that is rare IMO)

→ More replies (10)

2

u/Berberberber Mar 09 '16

Explicitly types on variables are useful for when you want to go through and change a dozen variable declarations because the return type of one method has changed, or when you want to waste time thinking about whether foo should be declared as ArrayList<T> or List<T> or Iterable<T> to the compiler even though it's always going to be whatever type the function returns.

7

u/SuperImaginativeName Mar 09 '16

Still catching up to C# I see

1

u/nzhenry Mar 10 '16

ha of course you'd get down-voted for that

3

u/DonKanish Mar 09 '16

LET.THIS.HAPPEND!

3

u/maestro2005 Mar 10 '16

One of the great things about Java is how explicit it is. The problem with automatic type inference is that the type is now dependent on context, and can change in subtle ways as seemingly unrelated code changes. There's a reason why a lot of Scala people start adding explicit types all over the place.

5

u/irarandomdude Mar 10 '16

There's a reason why a lot of Scala people start adding explicit types all over the place.

Only in specific places where it improves readability, not "all over the place". In most cases local variables and places where the type is super obvious declaring the type is not only unnecessary but clutters the code.

4

u/velcommen Mar 10 '16

can change in subtle ways as seemingly unrelated code changes

What do you mean? Can you provide an example. I'm having a hard time imagining this. The type of one function's output is the input type of the next function. So if I change the type of the first function's output, the second function will not compile. Unless, of course, the second function can also handle that type of input. But neither of those scenarios is a source of possibly subtle error.

There's a reason why a lot of Scala people start adding explicit types all over the place

In Haskell (because I can't speak for Scala), where there is whole program type inference, the convention is to decorate top level things (e.g. functions) with types, and leave off types for the majority of other things (e.g. variables within functions, nested functions).

Most of the time this works fine for me. I occasionally decorate a thing within a function. And if you don't have an IDE to to tell you the type, you can ask the compiler what the type should be by replacing something with a hole ('_'), e.g.

(foo :: [Char]) = map _ ["hello", "world"]

And the compiler will tell you that '_' should be replaced with a function from String to Char.

1

u/[deleted] Mar 10 '16

Did you read the title: Local-Variable Type Inference. In Scala preferred style is to add types for public API, but nobody except masochists will spread them all over their local method bodies.

2

u/elacin Mar 10 '16

Can we skip that pain and go directly wih val?

4

u/immibis Mar 10 '16

Java is not a language based on immutability*, and everything else is mutable by default - it would be completely inconsistent to only allow type deduction for immutable variables.

* I know you're going to bring up that thing about anonymous classes, so I'm going to pre-emptively point out that's considered a limitation and not a feature.

-1

u/ejonesca Mar 09 '16

Do you need a 'var' keyword at all? Can't you just have:

myNewVariable = 5;

without an explicit type declaration that doesn't actually add any useful info to the compiler? The compiler can just assume that any new unknown identifier is a new var.

87

u/ihcn Mar 09 '16

Then any typo becomes a new variable rather than a compiler error.

8

u/badcommandorfilename Mar 09 '16

This won't work predictably if "myNewVariable" already existed in an outer execution scope. The programmer may have intended to declare a new "i" variable for their loop, but instead they accidentally overwrite an outer loop's "i" - and this gets even harder with closures and lambdas.

Languages that allow this kind of implicit declaration have lots of weird scope gotchas that lead to some time-devouring heisenbugs.

10

u/Figs Mar 09 '16

Yeah, this is definitely one of my biggest gripes about the design of Python. To further expand on #4 in the common mistakes article you linked to as to just how surprising Python's scoping rules are because of the lack of var, consider this script:

$ cat example.py 
value = 1

def foo():
    print "foo:", value   # works fine

def bar():
    print "bar:", value   # throws exception
    value = 2

foo()
bar()

$ python example.py 
foo: 1
bar:
Traceback (most recent call last):
  File "example.py", line 11, in <module>
    bar()
  File "example.py", line 7, in bar
    print "bar:", value
UnboundLocalError: local variable 'value' referenced before assignment

Using the name of a variable in an assignment later in the function makes the whole function treat it as a local variable, even statements that would have previously worked. So, you can cause existing code to fail in really surprising ways by modifying code later in a function if you didn't realize that the name was already used to refer to something in an outside scope...

2

u/Berberberber Mar 09 '16

If you're going to allow implicit declaration, you have to have strict scoping rules, IMHO.

1

u/[deleted] Mar 09 '16

That's what downvotes aren't a disagree button. If /u/ejonesca didn't ask this question, It would have never occurred to why var was needed in the first place.

0

u/[deleted] Mar 09 '16

[deleted]

11

u/IbanezDavy Mar 09 '16 edited Mar 09 '16

Also a good example of why you default to strict pessimism in code and not do actions by default.

boolean launchTheNukes() {
    boolean shouldLaunch = false; // Gotta pass the tests first
    if (user.hasCredentials("canLaunchNukes") == Credentials.Authorized && 
        validateLaunchCode(user.enteredData) ) {
        shouldLauch = true; // Yay!!!
    }
    return shouldLaunch;
}

Let's not be launching nukes by default...

Some more examples of why this is bad...

boolean launchTheNukes() {
    boolean shouldLaunch = true; // Don't gotta pass the tests first

    try 
    {
        if (user.hasCredentials("canLaunchNukes") == Credentials.Authorized && 
            validateLaunchCode(user.enteredData) ) {
            shouldLauch = false; 
        }
    }
    catch(Exception e)
    {
         Log(e); // Awe, good job catching an error...too bad validateLaunchCode threw this...
    }
    return shouldLaunch;
}

Lesson kiddies? Fail by default. It saves lives!!!

4

u/[deleted] Mar 09 '16

Tester's fault.

13

u/eras Mar 09 '16

At least the tester is now ded, so that's resolved.

5

u/nemec Mar 10 '16
WONTFIX: No one left to test.

1

u/IbanezDavy Mar 09 '16

Depends where the nuke was aimed.

→ More replies (1)

2

u/Helene00 Mar 10 '16

He would be fine if he didn't run any integration tests...

1

u/s888marks Mar 10 '16

In this context, one would need to run disintegration tests.

2

u/FallingIdiot Mar 10 '16

Would worry me though if this would pass QA. You hope they test this stuff...

1

u/allofthesuddenmymane Mar 10 '16

this was proposed quite a while ago as well (2005 I think)

but that got shot down

1

u/_lerp Mar 10 '16

I don't know what all the commotion is about. You won't be able to use this in a production environment for at least the next two decades.

1

u/cowardlydragon Mar 10 '16

Just make groovy the new Java. Done.

Java keeps shifting around features that groovy has and does better for 5 years now.

1

u/nzhenry Mar 10 '16

Oh you mean like the feature that was introduced in C# more than 8 years ago?

1

u/nightfire1 Mar 10 '16

This would also make for a funny sort of compile time duck typing.

1

u/silveryRain Mar 10 '16

Type inference is pretty common in plenty of languages by now. Even C++ has it.

-12

u/mk_gecko Mar 09 '16

NOOOO. Please no!

11

u/nobodyman Mar 09 '16

Seems harmless enough; what's your concern?

4

u/[deleted] Mar 09 '16

[removed] — view removed comment

5

u/kmaibba Mar 09 '16

That's a cultural problem though. Somewhere, someone along the way decided that you MUST have an ISomething for every Something, and while we're at it, have an ASomething too! And then use an ASomethingFactory and an SomethingFactoryImpl to instantiate the SomethingImpl. To top it all off, offload all the EVIL MUST NOT USE "new" to a DI Framework and configure it in XML-files. That should do the trick. Your code is now "maintainable", because when you change something, you just have to implement the interface and the edit some XML file, as opposed to just changing one line of the fucking implementation. Fuck actually being able to debug and read stuff, right?

Got a new guy at work who writes code like this and it's a nightmare to read. I mean the actual implementation is 20 lines of trivial CRUD code, why do you need 4 support classes/interfaces spread over 3 packages? Why can't you you just write a simple class, write some tests and the do your silly abstractions the moment you actually need them (hint: you won't need them 99% of the time, and the other 1% you will need to change all the other stuff anyway because of unforseen new requirements).

OT though, I hope and am pretty sure that they won't implement the var keyword. All it does is reduce readability and save some keystrokes. Verbosity is not a bad thing. It might look clumsy when you compare it to some hipster language tutorial, and it might suck a little bit while writing the code, but when reading and understanding the code later, it's a godsend.

5

u/[deleted] Mar 09 '16

Do you really write Java without an IDE though? Pretty much all of them support hovering over the variable to see its type.

→ More replies (2)

-1

u/verydapeng Mar 10 '16

this can potentially break tons of codes out there

for example

my perfectly fine code today will not compile any more

Variable var = new Variable();

7

u/twofeetdown Mar 10 '16

"The identifier var will not be made into a keyword; instead it will be a reserved type name. This means that code that uses var as a variable, method, or package name will not be affected; code that uses var as a class or interface name will be affected (but these names violate the naming conventions.)"

From the article.

1

u/leafsleep Mar 10 '16

So var var = new Var(); will be valid Java?

1

u/verydapeng Mar 10 '16

this looks super ugly

1

u/[deleted] Mar 10 '16

New keywords were introduced before, e.g. enum. For legacy code, that's fine as long as you specify source version (which you should always do)

-16

u/probablytaken1 Mar 09 '16

Everyone hates javascript, everyone wants javascript.

24

u/eras Mar 09 '16

Though of course, this is not dynamic typing :).

→ More replies (8)

5

u/[deleted] Mar 09 '16

s/javascript/Haskell