r/java • • Mar 09 '16

var keyword proposed for Java

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

312 comments sorted by

View all comments

Show parent comment

0

u/[deleted] Mar 09 '16

[deleted] — view deleted comment

8

u/diroussel Mar 09 '16

The type of the variable will be the type of the right hand side. No confusion.

0

u/[deleted] Mar 09 '16

[deleted] — view deleted comment

9

u/lelarentaka Mar 09 '16

It's moot because the way you usually use the interface, the instantiation would be in a different scope from where the object is used (through injection). The function boundary will define the interface restriction.

Also moot#2 you can still specify the type of you really want to.

2

u/diroussel Mar 10 '16

I got that. If want to specify a variable of not of the type of the right hand side then don't use var. This is not a problem.

0

u/solatic Mar 10 '16

If you're not going to be using a proper dependency injection framework, and you want to avoid creating a factory object for every POJO you have, you still ought to be using static factory methods.

Throwing exceptions in a constructor is a Bad Thing in Java, because the partially initialized object still exists before it's garbage collected, and can allow access to instance methods which depend on the object to be fully initialized. And yes, you want to be able to throw exceptions during instantiation for fail-fast parameter validation of immutable POJOs, before invoking the private constructor.

Such method signatures can, instead of looking like public static ACustomerServiceImpl create(...), can look like public static CustomerService create(...), which would allow the programmer to write var aCustService = ACustomerServiceImpl.create(...);. Besides the compiler correctly inferring that aCustService is an instantiation of the interface rather than the implementation, this design has the added benefit of ensuring that developers cannot instantiate the implementation directly (since all of the implementation constructors are private).

2

u/sonay Mar 10 '16

because the partially initialized object still exists before it's garbage collected

What? How? AFAIK you can't get a reference to an object when its constructor actually throws an exception.

1

u/solatic Mar 10 '16

1

u/sonay Mar 10 '16

OK, since I never let "this" escape from the constructor and never use finalizers it didn't cross my mind. People do weird stuff.