The var stereo[type]

For quite some type I'd been strongly against using C#'s var keyword. I thought it was counter intuitive, that it was a sign of weakness, a way of saying you were not sure of the type of the variable you had used. But then it hit me, the power that lied within this simple construct had finally sunk in.


I started using var in unit tests, where it allowed me to write things faster, relieving me of tedious typing (pardon the pun). I was still in doubt, and at times used ReSharper to replace vars with actual types when I was done, but with time vars started to find their way in for good. I was surprised to discover I did not mind something was "var" as long as it had a proper name that clearly described its purpose in life. On the contrary, the ability to define something as "var" allowed me to codify my thoughts so much faster without dwelling on what type a particular variable should be (it should be whatever the force says it should be).

Var also holds a great benefit when it comes to refactoring, often saving you from cascading changes. If you have a method's result assigned to a var, and you change the type of the returned value, that var will still be valid. You might need to accommodate this change down the road, but your var will still stand its ground. Something you will definitely not be getting when using explicitly typed variables - tell that to someone who has a Dictionary<string,List<Tuple<int,string>>> that he now has to change to a Dictionary<Tuple<int,string>,List<Tuple<int,string>>>.

It wasn't long before most of my reference type variables were vars, and some of the primitives, unless something specifically prevented it (double - int division, and the likes).
Now that I'm cutting code in Java, I can honestly say I deeply miss having var around.
Var, I hope we will meet again, in this language or another.

I wish Java had a feature like var.
And LINQ.
And type inference.
And lambda expressions.
And actual generics.

Var, this song is for you.


Comments

Popular posts from this blog

Eclipse vs. IntelliJ, an empirical rant

Reflecting on reflection in Scala and Java