Thursday, March 06, 2008

Thoughts on General Purpose Implicit Typing

Ilya over at JetBrains recently blogged about the why the latest version of ReSharper is suggesting that you use the var keyword and implicitly type your variables as opposed to explicitly declaring types. 

I'm not sure if I'm down with this idea (yet).  Seems to me like this is taking a feature that was designed to tackle specific need for a compiler-deferred type assignment (Lambda and LINQ), and applying it with too broad of a stroke.

I don't disagree with Ilya's arguments in an idealistic sense, which tend to be focused around intuitive naming of your methods and properties.  That is no doubt are a great thing, but does the naming focus and implicit typing really make code better?  Will it help people who have difficulty naming methods and properties any better at it?  Saying that makes me think I'm saying "build practices for the lowest common denominator", but I think that naming can be a difficult thing sometimes.  Are there cases out there where type can't be inferred or formed from method name?

Also, I think there's something to be said about the fact that when reading C# your eyes focus on the left hand side of the assignment, and with the var keyword you're widening the focus needed to determine type.  Even if the variable is named in a manner that is blatantly descriptive of it's type, it still is easier to read for me.  For instance read the two examples below. 

var cat = GetCat();
var dog = GetDog();
var animal = GetAnimal();
 
Cat cat = GetCat();
Dog dog = GetDog();
Animal animal = GetAnimal();

Obviously the second one was easier to determine type.

For me, in principal, it all comes down to is whether or not it's true that the var keyword is a feature in the language or an evolution of the language.

For now, I'm going to hold off on this refactoring until these thoughts shake out a bit.

I'd like to hear what the C# language designers think about this.  I'd love to hear your thoughts as well.

2 comments:

Anonymous said...

I encourage you to work with it a bit and see what you think. One thing you'll notice is that by default, ReSharper only gives var as a "suggestion" when the initializer explicitly declares the type, e.g.

var dog = new Dog();
vs.
Dog dog = new Dog();

So far, I've been surprised at how often I end up thinking this improves readability.

ReSharper also gives var as a "hint" in the other places where you can use it--places like initializing a variable from a method's return value. While I can see Ilya's point, I'm still not quite ready to listen to those hints.

Unknown said...

Thế giới trò chơi : www.gameonlineviet.com
Kênh sức khỏe cho bé : www.tapchitonghop.com