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

27

u/GeorgeMaheiress Mar 09 '16

The text of the JEP raises a compelling point that hadn't occurred to me:

The need to provide a manifest type for every variable also accidentally encourages developers towards overly complex expressions; with a lower-ceremony declaration syntax, there is less disincentive to break complex chained or nested expressions into simpler ones.

My team has been struggling lately with this issue. Some developers hate long line-wrapped expressions, but often splitting them into smaller expressions doesn't shorten them much, as declaring the intermediate variables can cost as much as 30 characters.

5

u/kritzikratzi Mar 09 '16

get a bigger screen to avoid line breaks

16

u/stepancheg Mar 10 '16

People are not effective at reading long lines. Source.

6

u/b1ackcat Mar 10 '16

I also feel like chaining expressions like that results in hard to follow lines, even if it's not too many characters.

Something I tend to do to solve both these issues is to insert linebreaks between expressions. Similar to how you might use the builder pattern for a complex, highly configurable object.

String versionNum =
    VERSION_MAJOR + "." +
    VERSION_MINOR + "." +
    VERSION_BUILD_NUMBER + "." +
    VERSION_REV_NUMBER + "." +
    CURRENT_DATETIME_STAMP;

This way I'm maintaining the readability of each piece of the expression and not bleeding on forever on the same line.

4

u/[deleted] Mar 10 '16

In Guava you can just collect all objects that you want concatenated in such string and then use:

Joiner.on(".").join(collection);

Dislaimer: I know that many people don't like solutions depending on external libs but in real life how often you are not working in a big pile of code, where such dependency could rather make your code lighter than heavier? Than if your answer is still negative, I still would rather create my own clear solution instead of such concatenation.

4

u/vytah Mar 10 '16

You don't need Guava for that:

collection.stream().collect(joining("."));

But while I don't recommend pulling in Guava just for Joiner, if you happen to already have it in your dependencies (and it's damn quite likely), sure, use it.

→ More replies (2)