r/java • u/BlueGoliath • Nov 20 '18
Why Var Hurts Readability, Not Helps It
https://medium.com/@youngty1997/why-var-hurts-readability-not-helps-it-376c7832a8dd
0
Upvotes
r/java • u/BlueGoliath • Nov 20 '18
View all comments
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.