An Experiment in Scotch

"I write to discover what I believe." Michael Lopp on Twitter

Just Because You Can Doesn’t Mean You Should

Jeff Atwood recently wrote about the new var key­word in c# 3.0 and in essence came to the con­clu­sion that you should use var a lot more than you are so that your code is more con­cise. Richard Ding­wall shows why Jeff has missed the boat on this one. Jeff has writ­ten in the past that any time you can remove code you should. His exam­ple then was this one:

private string myString = "";
ver­sus this:
private string myString = String.Empty;

By writ­ing 10 less char­ac­ters in the first, your code is bet­ter. I think he missed the boat there in the exact same way he’s miss­ing it currently.

His new exam­ple involves “refac­tor­ing” 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 refac­tor­ing. It’s not elim­i­nat­ing a code smell, it’s not mak­ing the code more read­able, all it’s doing is 1) show­ing you know how to mis­use the var key­word and 2) show­ing you don’t much care about future code read­abil­ity and by exten­sion, the peo­ple who have to main­tain said code.

Richard gets it right by point­ing out that Jeff is right on one count, that hav­ing to declare what type you want twice in c# vari­able dec­la­ra­tions is silly. How­ever, you shouldn’t be tak­ing it upon your­self to “fix” the lan­guage by using var every­where. You go to work with the lan­guage 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 bet­ter than implicit.” Using the var key­word every­where you can is an exam­ple of the oppo­site and cer­tainly doesn’t make your code any cleaner or more explicit.


  1. Actu­ally, it is elim­i­nat­ing a code smell. It is apply­ing the DRY prin­ci­ple. In fact, I think that the var key­word is a code smell that the com­piler gods have inflicted upon us. I shouldn’t have to type it at all. Type Infer­ence FTW!!!!!!!1!!!1!

  2. Scotch Drinker

    June 26, 2008 at 11:14 am

    If by code smell, you mean “weak­ness of sta­t­i­cally typed lan­guages” , then yeah, I’ll buy it. I hear inter­preted lan­guages are all the rage these days.


Leave a Reply

Your email address will not be published.