Just Because You Can Doesn’t Mean You Should

Jeff Atwood recently wrote about the new var keyword in c# 3.0 and in essence came to the conclusion that you should use var a lot more than you are so that your code is more concise. Richard Dingwall shows why Jeff has missed the boat on this one. Jeff has written in the past that any time you can remove code you should. His example then was this one:

private string myString = "";
versus this:
private string myString = String.Empty;

By writing 10 less characters in the first, your code is better. I think he missed the boat there in the exact same way he’s missing it currently.

His new example involves “refactoring” this code:
StringBuilder sb = new StringBuilder(256);
UTF8Encoding e = new UTF8Encoding();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

into this code:
var sb = new StringBuilder(256);
var e = new UTF8Encoding();
var md5 = new MD5CryptoServiceProvider();

For one thing, that’s not refactoring. It’s not eliminating a code smell, it’s not making the code more readable, all it’s doing is 1) showing you know how to misuse the var keyword and 2) showing you don’t much care about future code readability and by extension, the people who have to maintain said code.

Richard gets it right by pointing out that Jeff is right on one count, that having to declare what type you want twice in c# variable declarations is silly. However, you shouldn’t be taking it upon yourself to “fix” the language by using var everywhere. You go to work with the language you have, not the one you want and all that.

All other things being equal, The Zen of Python had it right with “Explicit is better than implicit.” Using the var keyword everywhere you can is an example of the opposite and certainly doesn’t make your code any cleaner or more explicit.

2 thoughts on “Just Because You Can Doesn’t Mean You Should

  1. Actually, it is eliminating a code smell. It is applying the DRY principle. In fact, I think that the var keyword is a code smell that the compiler gods have inflicted upon us. I shouldn’t have to type it at all. Type Inference FTW!!!!!!!1!!!1!

  2. If by code smell, you mean “weakness of statically typed languages” , then yeah, I’ll buy it. I hear interpreted languages are all the rage these days.


Leave a Reply

Your email address will not be published. Required fields are marked *