Friday, November 21, 2008

The Misuse of var in .NET - it's bad programming!

This post will argue that many .NET developers misuse implicit typing (var) in their programming. I see this more often and I really think this is really, really bad programming. This is why:

About implicit variables
Fist of all, what does the documentation say about var?
var keyword[C#]:
"Variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:
var i = 10; // implicitly typed
int i = 10; //explicitly typed

Overuse of var can make source code less readable for others. It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types." Many developers do not read the remarks text and I can also add that if you are looking at var [C#] instead of the var keyword [C#] this warning is less obvious. So when should you use it?

How to use var
var is a way of implicitly create a type, an temporary anonymous type. Note that this is not the same as variant in other languages. This means that the variable is still typesafe and can not change its type. For example the variable "i" in var i=10; can not be set to i="foo";. When declaring "i" we will implicitly say that i is an int. var is powerful for example when we use LINQ. It is a way of letting .NET help us create a temporary type for us (it is often temporary since it can only be used for local variables).
var somePerson = new { SomeProperty1 = 10, SomeProperty2 = "Foo" };

var persons1
= from p in Person
where p.Age == 30
select p.Name;

var persons2
= from p in Person
where p.Age == 30
new { p.Name, p.Age, p.EyeColor };

In persons1 the type will be a string (if p.Name is a string) and in persons2 it will be a temporary type containing name, age and eye color. This is a ok syntax and it is also a very powerful feature. Implicit typing can also be used in lambda expressions but sometimes I think it makes the code unreadable. What about my rage against var?

How not to use var!
A colleague of mine has a motto that says: "Any fool can write code that a computer can understand. Good programmers write code that humans can understand." In a time where usability and collaboration with people is key features you must write code that anyone can understand and that is self-explaining. Lately I have see more and more misuse of var and here are some examples of misuse:
var sample1 = 10; // Why not just type int? Maybe I really wanted a double?
var sample2 = GetPersonName(person); // What will be returned, an object, a string?
var sample3 = someReference.DoSomethingReallyFancy<ReallyStrangeObject>(); // Same as above!
var sample4 = new MyClass(); // Maybe ok?

The first sample is just stupid and makes the code hard to read. As the comment say, maybe you really wanted a double but forgot the ".0", this can be hard to see in debugging a calculation. In sample2 you really have no clue what type of object the method is returning. Sure you have intellisense but you should NEVER have to use intellisense to read code, maybe you are in an editor without intellisense. Sample3 is the same as sample2 but in a more complex format. I see this a lot and I hate it! Sample4 is not my favorite but it can be ok if you have a really long class name. In this samploe you can see the type in the declaration. I see a small risk here and that is if you refactor sample4 to a factory or some method, then sample4 will be the same as sample2. In this short context these use of var might not seem to ugly, but try a method that only uses var to declare its variables and get all instances from other methods and then do some fancy stuff with it. I promise you that the code will be hard to read bot for you and especially for another developer.

I think this use of var is really bad programming and I think that developers that use this type of coding are bad developers writing bad code, so please stop the misuse of var! Please!


Anonymous said...

I think this is mostly due to Resharper suggesting it.

They seem to be dead set on keeping it that way though, so all we can do is continue the war.

Xerxes said...

I for one am with you on this. I dislike the use of var exactly as you've outlined, and turn off the "use implicit variable" suggestion from ReSharper as soon as it's installed.

It's not hard to press the correct letters on your keyboard to give your locals an explicit type, and takes almost no longer than it would to type "var".

Why you wouldn't want to do everything you possibly could (with ease) to make your code more readable is beyond me.

Ramon said...

var is the best thing since sliced bread!

The problem you have here is good variable names. THAT should indicate what it contains.

Anders Bursjöö said...

Ramon - Sad to say but you could be a very bad thing for usability. So what you say is that you want Hungarian Notation on your variables? Am I missing something or how do you make your code (all code not only a simple example) readable with var, how do you make it easy for another developer to understand your code?

"Any fool can write code that a computer can understand.
Good programmers write code that humans can understand."

Ramon said...

Hungarian notation? I didn't write that :)

The variable name should mention what is stores:

Althoug I do not favor var for structs as these are so low level but still..

var personFullName = GetPersonName();
var personAgeInYears = 10;
var personFactory = PersonFactory.Create();

Anders Bursjöö said...

Ok, I understand. How do you think;
var personFullName = GetPersonName(); helps the developer understand what kind of object personFullName is? Is it a string or is it an object that describes first name and surname?
I do agree with you that you should have very describing field names and that is also a very good programming practice. But by write var as your type you are almost required to write even longer names than otherwise? Why use var when you can help someone understand your code by being explicit?

Ramon said...

Well.. I would just assume bij the name that it is a string and if not when my mouseover or compiler error will help me.

When I'm 'reading' code then I'm not that interested in types. I'm interested in behavior thus good naming conventions for methods, members and variables help me more.

And besides.. it is very personal just as for example bracket placement and such.

Anonymous said...

Ramon said:
"When I'm 'reading' code then I'm not that interested in types."

So you have no idea of what you are doing.

The type of the variable is everything.

Ramon said...

The type is only a carrier for data in a context. The type only indicates if the data is stored efficiently. The context in which it is used indicates if the data is used efficiently regarding usages in reads/writes.

Methods shouldn't be larger then one screen. With current resolutions even smaller. var's can only be used within methods so their scope and type can easily resolved when needed which probably is almost never.

jty said...

I know my comment comes in late but please for the love of god be explicit... period... end of discussion.

Joel said...

The only reason that I can see to use var when the type is known is to make less work for the developer, which amounts to laziness. The more self-describing code is, the better it is.