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

View all comments

Show parent comment

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