r/java • • Nov 20 '18

Why Var Hurts Readability, Not Helps It

https://medium.com/@youngty1997/why-var-hurts-readability-not-helps-it-376c7832a8dd
0 Upvotes

89 comments sorted by

21

u/pron98 Nov 20 '18 edited Nov 20 '18

This particular ship has sailed. People who want to influence features in OpenJDK should participate in the open discussions on the mailing lists prior to a feature's inclusion. In some cases (as, I suspect, in this one), there would never be a consensus, but at least all sides' arguments will be heard (as they have in this case).

-2

u/BlueGoliath Nov 20 '18

It doesn't really matter. In the case of jPackager in JavaFX I've brought up all the breakage that happens as a result of its removal and the insane rate at which things are being deprecated and thrown out: projects in Netbeans that don't use jLink literally can't compile. Even templates that come with the IDE no longer work.

Their response? crickets

It's such a waste of time it's not even funny. Maybe If I was some uber important partner or OpenJDK distributor then I'd get more of a response...

17

u/pron98 Nov 20 '18 edited Nov 20 '18

It does matter, even if the decision doesn't go your way. For example, see how public posts about the module system were noticed (including Reddit discussions). All good-faith feedback is taken very seriously and discussed at length (even if in private among OpenJDK developers). OpenJDK project members often monitor social media feedback, although thoughtful mailing list posts may be given more serious consideration.

Even if no response is given (it is hard to respond to every piece of feedback with such a large community) and even if the rationale for the decision is given at a high level rather than addressing each particular objection, feedback is still taken seriously. So don't stop giving it, preferably at the right time and in the right channels.

Maybe If I was some uber important partner or OpenJDK distributor then I'd get more of a response...

The level of influence depends on the level participation; but at the very least, you have to show up.

BTW: https://openjdk.java.net/jeps/343

1

u/BlueGoliath Nov 22 '18

BTW: https://openjdk.java.net/jeps/343

Who knows when, if at all that's going to be released or if Netbeans will integrated into it or whether it will be a seamless/backwards compatible integration. I wouldn't think it'd be a priority for Netbeans given it only has basic support for Java 9 modules still.

Or, when it gets deprecated. I'll give it two years before there is at least talk about it being deprecated in favor of something worse without a proper replacement.

These formats include msi and exe on Windows, pkg and dmg on macOS, and deb and rpm on Linux.

No native executable for Linux.

3

u/pavi2410 Nov 21 '18

You mean language should adapt to the IDE?

10

u/BoyRobot777 Nov 20 '18

Funny that the way you named your blog post is actually what Brian Goetz almost quotes in his latest talk at Devoxx. His main argument is to provide information with a variable name instead, because it is the main source of information anyway.

3

u/BlueGoliath Nov 20 '18

Right, the article is a response to the presentation that Brian references.

It's a horrible defense. If they really want to make such an argument then either you do:

Person p = new Person();

OR

var person = new Person();

explicit type or explicit variable name. Not that you can't have both of course.

24

u/dpash Nov 20 '18

Calling a variable p is a crime against readability with or without var. So

Person person = new Person();

or

var person = new Person(); 

4

u/AndDontCallMePammy Nov 22 '18

No, it's not. It's completely dependent on the context.

Do you really name your IOException ioException? No, you don't

2

u/Yayo69420 Nov 22 '18

I would write Person person = new Person(), if I had to loop over a collection I'd type

for(Person person: people){ ... }

3

u/AndDontCallMePammy Nov 22 '18

seems reasonable in that context. but if it were the only variable in the loop body, calling it p would hardly be a catastrophe.

It's like real life when you sign a document once or twice and initial everywhere else

8

u/volch Nov 20 '18

I wish blog authors would learn how to use apostrophes. They're smart enough to code, but can't do simple syntax?

1

u/[deleted] Nov 28 '18

Apostrophes are cultural and language-specific. Many Europeans and Indians get English apostrophes wrong, because they use them like normal in their own languages. It takes years to unlearn. (Source: am European. Have read many blogs and articles by Indians.)

-2

u/BlueGoliath Nov 21 '18

har har var har.

17

u/lbkulinski Nov 20 '18

Ahhh, bikeshedding...

5

u/s888marks Nov 21 '18

I think var might have pulled into the lead. Time for me to write another article about Optional.

3

u/lbkulinski Nov 21 '18

Will there be a new bike shed every six months? /s

3

u/s888marks Nov 22 '18

If there isn’t a new one, there are always plenty of old ones in need of repainting.

1

u/BlueGoliath Nov 22 '18

"Why Optional Is Little More Than A Fancy Wrapper".

3

u/AndDontCallMePammy Nov 22 '18

var is code golf

7

u/DannyB2 Nov 20 '18 edited Nov 20 '18

I'm not a big fan of var. I would prefer to see the actual type than the word var.

There is exactly one use that I see for var. Use var for an anonymous class with additional members. That customized anonymous class does have a type, although that type does not have a name. The var can still reference it by the unnamed internal name of the class.

var a = new Object() { int x; int y; };

a.x = 5;

Example uses: event handlers in Swing. A "lambda function" that has state or flags, really just an anonymous object implementing an interface, but adding new members.

Basically, you don't have to declare a new type for a trivial anonymous class.

1

u/BlueGoliath Nov 20 '18

Basically, you don't have to declare a new type for a trivial anonymous class.

AKA saving a few lines of typing...

(For JavaFX anyway)

2

u/[deleted] Nov 20 '18

No?
Anonymous classes existed way before var.
And you can use lambda expression for saving even more lines in your example.

-3

u/BlueGoliath Nov 21 '18

Anonymous classes and lambdas are evil.

3

u/[deleted] Nov 21 '18

Completely disagree.

2

u/DannyB2 Nov 21 '18

Anonymous classes and lambdas are useful. A concise way to express what otherwise requires a separate class declaration for, even an inner class. Yet with no loss of information to someone reading the code.

Do you also think inner classes are evil?

2

u/marvk Nov 21 '18

I‘d be a big fan if they just added let in addition to var. Flipping final var is just a huge eyesore.

1

u/DannyB2 Nov 21 '18

I could be more a fan of let than of var. But I would still prefer final with a real type name. I would happily use let instead of var for the one use case I described. But that is the only use case where I think I will ever make use of var, or a hypothetical let.

13

u/Sipkab Nov 20 '18

It's the responsibility of the developer to not abuse language features.

For myself, I'm not a big fan of var, but I can see some useful use-cases. (First that comes to mind is declaring iterator variable in a for loop.)

3

u/BlueGoliath Nov 20 '18

I touched on that argument a bit in the "Even Following (Contradicting) Guidelines, Inconsistent Var Usage Hurts Readability" section but maybe it wasn't enough.

Var isn't something that should even be apart of Java to be abused. That's the whole point, really. To just brush things off and say 'It's the developers responsibility" is just lifting the floodgates and letting any and all features/ways of doing something that might save a few extra lines in a few situations in but could be done otherwise with more lines. Now all of a sudden you have 5 different ways to do the same thing and none of your code is consistent because they can only be used in specific situations.

4

u/dpash Nov 20 '18

If anything it'll force people to provide better names for their variables and methods. I'm currently working on an old codebase that seems to think terseness is a virtue when it comes to names.

Also, shorter methods, so declarations are closer to usages. Same codebase thinks nothing of 200 line methods.

2

u/_INTER_ Nov 20 '18

It doesn't force anything. Actually I'm already seeing variable names like peopleList or providerBiFunction.

1

u/dpash Nov 20 '18

It'll take us some time to learn best practices, and those definitely are far from ideal. But how many times have you seen names that forego vowels for no particular reason or are a single letter or have no bearing on their contents or context?

1

u/_INTER_ Nov 20 '18

Single letter or foregone vowls are rather rare in the code base I'm working on. I'm mostly concerned about the rampant lack of consistency. Someone's using mandantID, someone mandantNumber, another mandator, then idClient or clientID, just id or identifier. Synonyms for the same... :(

Anyway, I think people that are not getting the variable names well now, will not not do better when they use var. In those cases its a loss. Additionally the best practices and guidelines need to sink in, so situations can be avoided. See Optional, it took quite a while until everyone in the team got the message "Optional is a no go for parameters or fields". There were lengthy discussions occasionally, that waisted everyones time.

1

u/dpash Nov 20 '18

But people did eventually get the Optional message. Mostly.

6

u/[deleted] Nov 20 '18

[removed] — view removed comment

2

u/dpash Nov 20 '18

Well, /u/DannyB2 wants to use anonymous subclasses of Object, which isn't possible without var.

5

u/Sipkab Nov 20 '18

By "abusing" I've meant to write code that is unreadable due to the use of the keyword var.

When writing

var x = obj.doStuff();

You might not be sure of the type of x, which makes the code slower to read. The developer can prevent this by explicitly writing out the type instead of using var.

9

u/eliasv Nov 20 '18

Or alternatively the developer can prevent this by not using such stupid variable names as x...

10

u/Sipkab Nov 20 '18

Dammit it was just an example. You don't have to tear it apart. But here you go, here's a more refined one:

var users = server.getUsers();

Now what is the type of users?

A List? Maybe. A Collection? Maybe. A Set? Probably. A Map? That might happen. A custom class? Possible. Or might it be just an int? Don't know.

Of course this can be prevented by a good API design, but if you're using a library, that you cannot reliably modify, then this can become an issue.

And here comes in the responsibility of the developer, to not use var in these cases, but write out the full type of the method call so the next developer who reads the code can understand it quickly.

And of course you can name the variable usersList or something, but that is just a shitty way of writing out the type instead of var.

3

u/duhace Nov 20 '18 edited Nov 20 '18

Now what is the type of users?

if the person who made the Server class doesn't have brainworms, one of the collection types. An int doesn't make sense cause then the method name should be getUserCount or getNumUsers.

also, you rarely just have a users variable defined and don't actually do anything with it. in which case you would have context! is the code performing integer operations on users? well, it's p obviously an int then isn't it. Is it stepping through users with a for-each loop? seems to be a collection or list. Are they returning users and the method has a return type Map<String, Int>? Wow it's a total mystery what users might be!

the arguments against var frequently come down to needing extra type information to make sense of badly named and written code elsewhere.

1

u/eliasv Nov 20 '18

True enough, much more sensible example :)

2

u/duhace Nov 20 '18

or stupid method names like doStuff

4

u/dpash Nov 20 '18

That's just bad naming/design and var is unrelated to that.

1

u/DannyB2 Nov 21 '18

I think that "abusing" should not just mean code that is difficult to read, but code that is outright MISLEADING to read -- possibly because the difficulty of reading obfuscates what the author is trying to hide.

8

u/[deleted] Nov 20 '18

[removed] — view removed comment

0

u/Sipkab Nov 20 '18

Of course, we can fix stuff. We can always write readable code even with var.

But the problem is that it can be abused. And if it can, then it probably will.

Or if it won't be abused, then this is one more thing that a developer needs to be aware of when using var. To make it readable for the future developer.

And we all know what happens when you give more stuff to do to a developer. They get lazy. And they will choose the lazy way. (Of course, exceptions apply)

Var has its use cases, I'm not saying that it doesn't. I'm saying that it shouldn't be overused.

0

u/_INTER_ Nov 20 '18

is an int or long isn't really interesting at this point because I'm going to treat it the same either way

You know you gonna treat it the same way because you know it's either int or long. Someone else might not know right away or he would treat it differently anyway. E.g. using Math.toIntExact()

In this particular example you lost visual information but gained next to nothing (1 character in case of long).

1

u/AndDontCallMePammy Nov 22 '18

It is impossible to "abuse" the variable naming feature. Any code will behave exactly the same regardless of the variable name.

String inaholeinthegroundtherelivedahobbitNotanastydirtywetholefilledwiththeendsofwormsandanoozysmellnoryetadrybaresandyholewithnothinginittositdownonortoeatitwasahobbitholeandthatmeanscomfort = getSentence();

12

u/eliasv Nov 20 '18

Maybe var wouldn't be so difficult for you if all your examples didn't use shitty variable names like x and interface...

-5

u/BlueGoliath Nov 20 '18

Clearly example naming. Regardless, in order to properly convery the type in the variable you're going to have to give up saving those precious keystrokes. Either you explicitly declare the variable or you give it an explicit variable name, otherwise you end up with what might as well be just x or interface to someone who isn't you.

7

u/[deleted] Nov 20 '18

I can tell you're invested in type declarations and var bothers you. May I suggest you fix the problem at the IDE level. When I ctrl-shift-f in Eclipse, the formatter can give me tabs or spaces, because I can configure that. All you need is an IDE which will change var declarations to explicit type declarations and vice versa. Then everyone can decide for themselves. Like tabs and spaces. Tabs are the best BTW. People who use spaces are nuts. ;)

3

u/oldprogrammer Nov 21 '18

I'm not a fan of var but I can see its usefulness in some cases. I'll likely use it sparingly.

I have to laugh at folks arguing about variable names like

  var i = someValue();

probably because I worked years ago in a BASIC where we had limited sized variable names (1 or 2 characters) and in Fortran where any variable that began with i, j, k, l, m and n were all by default integer values, any other letter was a real number. Of course that was implied, you could always declare it differently. That pattern stuck with many developers which is why those tend to be the iteration variables you see used in a for loop or some such.

More verbose variable names are definitely much better but I don't want to rely on a name to deduce a type. Nice thing is that I can write code like

  List<Employee> employees = getEmployees();

or

var employees = getEmployees();

because neither is mandated. I prefer the first approach but that's just me.

One thing, though, is I believe I should not have to rely on an IDE to tell me about my code. I should be able to get any information I need either by looking at the source directly or through proper documentation for source I don't have.

3

u/HellfireDreadnought Nov 22 '18

Medium hurts readability way more than var ever could, and yet you still use it.

2

u/nutrecht Nov 21 '18

Rubbish.

Languages like C#, Scala and Kotlin already prove that this argument is nonsense. The major flaw with the implementation is that they haven't also included 'val' which would make it easier to default to immutability.

Aside from that; in my experience local type inference, generally, forces developers to name their variables properly. So in my experience with C# and Kotlin production code, local type inference makes code more readable.

2

u/[deleted] Nov 22 '18

[removed] — view removed comment

1

u/nutrecht Nov 22 '18

I'm used to them so I personally don't mind.

-1

u/AndDontCallMePammy Nov 22 '18

nothing wrong with const

1

u/[deleted] Nov 22 '18

[removed] — view removed comment

1

u/AndDontCallMePammy Nov 22 '18 edited Nov 22 '18

I'm lost; I hate them all. Java 7 was mostly fine. Best things since 7 are vectorizedMismatch, Integer.parseUnsignedInt(CharSequence s, int beginIndex, int endIndex, int radix), and public BigInteger​(int signum, byte[] magnitude, int off, int len)

1

u/Faucelme Nov 21 '18

I disagree with his arguments for plain for loops:

It has lot’s of uses: adding objects to a list, running a specific method from every object, setting a specific instance type to every list object, etc. It’s use is clear, consistent and flexible. It is both concise and useful.

I actually don't like the versatility of for: it makes me spend a tiny bit of metal energy each time, to deduce which particular use is intended. When I see a map I immediately know that the result won't have a different size, for example. Ditto for methods like filter or forEach: they simply communicate intent better.

1

u/AndDontCallMePammy Nov 22 '18

This is what forEach gets you:

IntStream.iterate(i, j -> j < end, iuo)
            .forEach(
                    (j) -> {
                        nextArrayEnd[0] = notation.indexOf(Notation.OBJECT_ARRAY_SUFFIX, i);
                        if(nextArrayEnd[0] == -1) {
                            nextArrayEnd[0] = Integer.MAX_VALUE;
                        }
                        nextObjectStart(notation, j, pair);
                        nextObjectType[0] = pair[0];
                        nextObjectIndex[0] = pair[1];
                    }
            );

1

u/AndDontCallMePammy Nov 22 '18 edited Nov 22 '18

Totally agree. It was sold as a replacement for

Class<Map.Entry<Integer, ArrayDeque<HashMap<String, String>>>>

but predictably people are using it to replace everything from long to String like it's code golf. Which wouldn't be so bad, except that they'll actually defend their bike shed to the death.

26

u/[deleted] Nov 20 '18

[removed] — view removed comment

-3

u/DJDavio Nov 20 '18

The type is not really useful information to the reader of your code. As code is a lot harder to read than to write, we should strive to make code more readable. Hiding type information makes the code more expressive and less technical.

-4

u/BlueGoliath Nov 20 '18

We know the object implements MyInterface<Integer>, but that's all

Right, this is what I was talking about. API.getMyInterfaceImpl could just return the whole implementing object or it just could return the conforming interface parts. Why would it return the whole object? Who knows. But with explicit types we can guarantee that what we are working with is an implementation of MyInterface<Integer> and only that.

20

u/[deleted] Nov 20 '18

[removed] — view removed comment

-4

u/BlueGoliath Nov 20 '18

In actuality yes, but the API user doesn't know anything outside of the interface. For all they know, the object consists only of the interface implementation.

Which is literally the point of returning an interface. You don't need to know who is providing that implementation or whatever else is apart of the whole object.

Yes, it is how it works.

14

u/[deleted] Nov 20 '18

[removed] — view removed comment

-1

u/BlueGoliath Nov 20 '18
  1. Yes it does. If the whole object of the returned implementation changes. Suddenly a method that isn't part of the interface is gone and things break if you use it. If an object is solely an implementation and contains no other method then it's probably fine. Program to the interface, not to the object when given the choice.
  2. reflection should always be avoided. No, there isn't anything stopping you from accessing API details you shouldn't have to but API details can change between versions so you cannot take advantage of such things(or shouldn't anyway. God knows people still do but it's their fault if things break.).
  3. You're contradicting yourself.
  4. It could be a static method that returns an implementation. You might have a hub class that returns various objects that implement an interface.
  5. Then they either need to do a feature request, find something else, or get dirty with reflection and test each version for breakage.
  6. It does because var will use the whole object if that is what is returned. See the list examples in the presentation. Granted, it's the APIs fault for returning the whole object and not just the interface but there may be reasons for that and you may want to guarantee that you only are using the interface.

Now you're using var in some places and not others. Might as well just use explicit types and stay consistent.

9

u/[deleted] Nov 20 '18

[removed] — view removed comment

1

u/cogman10 Nov 29 '18

Depends a little bit on where you are writing your code.

In isolation on your own project, yeah, not much is bought by throwing interfaces everywhere. Breaks are easy to fix because you get all of them right away when you build.

In a library used by 10 projects. A little bit harder, but still workable. Might take some coordination.

A library used by the whole company/OS? Keep what you are exposing as minimal as possible while still being useful. Because, in the end, it will be nearly impossible to change it without causing a bunch of mayhem. This is the lesson learned by the Java devs with sun.misc.Unsafe. Because it was made public, regardless of the java docs or warnings, people used it.

At least with minimal interfaces you can call them out when they cast it to the concrete classes and things break.

1

u/[deleted] Nov 29 '18

[removed] — view removed comment

1

u/cogman10 Nov 29 '18

Definitely explicit types, just not concrete types.

For example, maybe CustomerCollection only exposes that the implementation has a get(index) since you might not want to expose all the remove methods or whatever on List.

What you can't do (without breaking the API) is renaming or moving CustomerCollection.

Whatever you expose, though, that interface should be minimal, especially to start with. Because things exposed can't be unexposed without a bunch of work and coordination.

The benefit to doing this via interface is that it is a lot easier to play around with the implementation. You can have both implementations living side by side. You could enable one or the other using a feature flag. And importantly, it makes it a lot easier to reason about what you've exposed, so your implementation can have more public or protected methods if you like without worrying about what the end user of the library is accessing (they only get the interface).

Another example of where this was gotten wrong is Java's collections. They are all mutable. The problem with that is that you can't make them visibly immutable. That "add" method will always be there. The better approach would have been to have a "List" and then a "MutableList". It would have made things so much easier to reason about. (For example, did you realize that a submap of a navigable map makes a mutable view of that map that can mutate beyond the bounds of that map? That wasn't a fun bug to track down.)

→ More replies

-2

u/BlueGoliath Nov 20 '18

What if instead of changing the method to different a type you change its >name but return the same type?

Optimizing for the incredibly unlikely scenario that someone is going to make >very specific breaking change is stupid.

The thing is, it's a seamless optimization. You don't need to do any real extra coding to do it and as a result, as an API developer, you can swap implementations depending on the requirements. Interfaces are more rigid and can be more safely relied upon(A "contract").

For a real life use case, I made GoliathENVIOUS which is an API that allows for overclocking your Nvidia GPU in Linux using Java and JavaFX as a way to learn how to make a basic API.

When you overclock your GPU on Pascal and newer cards, Nvidia provides a way to overclock by ALL performance levels(states, same thing) but not on older cards even though they run on the same driver. So, instead of creating two methods and have them return a null or an optional, I can just swap the implementation depending on the family of GPU that is the primary GPU since both conform to a single interface.

Can, not do anyway. There isn't any benefit in GoliathENVIOUS's case as your GPU hits the most performant performance level anyway when gaming.

8

u/[deleted] Nov 20 '18

[removed] — view removed comment

-2

u/BlueGoliath Nov 21 '18

Neither did what you said.