I hate var and so should you!

Have you ever been writing a piece of code and ended up writing this?


var myReallyObject = GetMyReallyCoolObject();

If yes, please do a favor to everyone and remove that var. It’s not doing any favors to anyone; it’s just reducing the readability of code. If you’re not using a decent IDE, you can never know what that var actually is. In Visual Studio, you’ll need to hover on the var keyword to discover what it actually is. All it did was inconvenience to anyone who’s going to read your code.

Moreover, a var can be a ticking time-bomb, waiting to explode. How? Great Question! Let me illustrate.


private bool RandomFunc()
{
    var myRandomNumber = GetRandomNumber();
    return IsRandomNumberInRange(myRandomNumber)
}

private bool IsRandomNumberInRange(int num)
{
    return num > 10;
}

private bool IsRandomNumberInRange(double num)
{
    return num > 50;
}

private int GetRandomNumber()
{
    return 42;
}

If along the way, GetRandomNumber’s return type changed, the code will still build properly, but the functionality changes. Eliminating the use of var simply resolves this inconsistency. Obviously that’s a trivial piece of code but the rules still apply.

Of course, there are excellent uses of var. I use it when I’m trying some LINQ out and I could not be bothered to guess the return type of some really long LINQ operation, as illustrated.

Given a list of Students (Name and Mark)


List<Student> students = new List<Student> { new Student { Name = "Albert", Class = "1A" }, new Student { Name = "Herd", Class = "1A" } };

Doing an order by and group by on such operation will result in a complex object. I’d rather see


var grouped = students.OrderBy(student => student.Name).GroupBy(student => student.Class);

than see


IEnumerable<IGrouping<string, Student>> grouped = students.OrderBy(student => student.Name).GroupBy(student => student.Class);

I mean, adding that complex declared type provides no real business value; besides in this case we’re not interested in the specifics of the type.

Here’s my thoughts when you can use var:

  • When the return type is complex and we’re not really interested in the return type. Focus on the business part rather than the technical part.
  • When you initialize the variable in the same line using a new construct.
  • Anonymous Types.

Here’s my thoughts when should NOT use var:

  • When the overall readability of code is being impacted.(For me, this is the deal breaker)
  • When the variable is being initialized using a method call.
  • When having a var introduces the possibility of changes in behavior of the variable.

So please, don’t just used var for all your declared types; use it with common sense.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s