I would like to suppose a new rule for Java Sonar about the “var” keyword.
My first reaction about it was “What the hell? Is this a scripting language now?” And this has not change must, but still a bit.
The problem with usage of var is, that a code reader has a harder time to understand the code, because a variable’s type must be researched by analysing further code. Well, one could argument, that the type does not matter to understand the code. But I think, we all know, that is is untrue. Though there might be situations, where this is indeed true.
I would have preferred the language designers to avoid this step. Though I always thought, it was designed in the wrong direction. But this thought leads me to this rule proposal.
The motivation for the var keyword was certainly to avoid redundant notation of possibly long class names.
MyClassWithLongName x = new MyClassWithLongName();
Unfortunately the possibility to use var for declaration opens the world to bad code like this:
var y = executeSomeMethod();
or:
for ( var z : list ) {}
In both situations you have to further analyze the code to know the type or use the IDE and hover over y resp. z.
I would like to suppose a rule, that generally marks the use of var as error, warning or code smell or what ever, with one exception: constructor calls.
The rule should ignore lines like this:
var x = new MyClassWithLongName();
In this case nothing is left to imagination or analyze.
Maybe accepting constructor calls for var should be a configuration flag.
The rule should have another configuration flag to tell, whether to accept constructor calls with generics like this:
var x2 = new MyGeneraicClass<>( arg0, arg1 );
In this case generics need to be researched again.
What do you think? Is there a chance for a rule like this?