Click here to Skip to main content
Click here to Skip to main content

"Var keyword is for JavaScript" - about using the var keyword & other coding guidelines

By , 31 Mar 2010
Rate this:
Please Sign up or sign in to vote.

Introduction

Today I was reading an article on CodeProject, and I was really astounded by the way some people rate articles and give comments...

It was an article about someone who had implemented a simple service locator which contained the following code sample:

using System; 
using CuttingEdge.ServiceLocation; 
using Microsoft.Practices.ServiceLocation; 

public class Global : System.Web.HttpApplication 
{
  protected void Application_Start(object sender, EventArgs e) 
  { 
     // 1. Create a new Simple Service Locator container 
     var container = new SimpleServiceLocator(); 

     // 2. Configure the container 

     // Register a delegate that will create a new 
     // instance on each call to GetInstance. 
     container.Register<ISamurai(() => 
     { 
        var weapon = ServiceLocator.Current .GetInstance(); 
        return new Samurai(weapon); 
      }); 

      // Register a single object instance that always 
      // be returned (must be thread-safe). 
      container.RegisterSingle(new Katana()); 

      // 3. Register the container to the Common Locator 
      ServiceLocator.SetLocatorProvider(() => container); 
    } 
}

which seems quite obvious to me. Since I noticed a comment titled 'my vote of 2', I was curious why this article would be voted such a low score (2 out of 5). I checked the comment and I was astounded:

Please note: the keyword "var" is supposed to be used with anonymous types. You should not use it for anything else. Otherwise please start programming java script

Who Cares?

Actually, I do.

Since I could not resist I posted the following comment:

Ahum... there have been numerous issues about this, but in general it should not pose a problem, because it is quite clear what its intentions are at the beginning;
i.e.:

var sl = new SimpleServiceLocator();

is not really more obvious than:

SimpleServiceLocator sl = new SimpleServiceLocator();

In fact, the information in there is the same, but the second one is more verbose, so every person in his right mind would opt for the first alternative.
This might be different if you use a function which does not directly expose the return type in the function name; i.e.:

var x = SomeFunction(y,z); 

This is considered bad practice by most.

This one is not:

var myservice = sl.Resolve<IMyService>();

Because the initialization contains enough obvious information to give pointers to the var's type.

So, if this is the only reason why you are giving a 2 (the author has obviously invested quite some time in this article), then you might need to start doing some JavaScript yourself.

After tweeting about this, I had an interesting conversation with @JacoPretorious about this, who says he uses var everywhere, but pays more attention to variable names.

While I understand what he means, IMHO variable names should not infer the type, only the meaning of the content if necessary.

I personally think there is nothing wrong with using single letters as variable names, as long as the intent is obvious. This is an example that is perfectly valid IMHO:

public bool InvalidateCustomer(int CustomerId)
{
  var c = sRepo.GetById<Customer>(CustomerId);
  if ( c.Orders.Where(o=>o.PaymentReceivedOn==null).Any()) 
    return false;
  c.Valid=false;
  sRepo.SaveOrUpdate(c);
  sUOW.Commit();
  return true;
}

This one is not IMO:

public class MyProcessQueue
{
  public void ProcessQueue()
  { 
    for(;;)
    {
       var p = Queue.Next();
       if (p==null) 
         break;
       sProcessor.Process(p);
    }
  }
}

Since you cannot infer the type from Queue, you should make the type explicit:

public class MyProcessQueue
{ 
  public void ProcessQueue()
  {
    for(;;)
    {
       Order o = Queue.Next();
       if (o==null) 
         break;
       sProcessor.Process(o);
    }
  }
}

This would change if the MyProcessQueue would be a generic class:

public class MyProcessQueue<T> where T:ISomeInterface
{
  public void ProcessQueue()
  { 
    for(;;)
    {
       var p = Queue.Next();
       if (p==null) 
         break;
       sService.Process(p);
    }
  }
}

In this case, I think you have enough information available to know that the type should be about the generic class. Using more explicit names for the variables does not add a lot of information for me; I do not find the following (exaggerated) example more obvious than the previous one; in fact, it takes more time to get the intent here, because your mind needs to process more information (also note the comments, which do not provide any extra information to me):

public class MyProcessQueue<T>
  where T:ISomeInterface
{  
  // Process all jobs in the queue, until there is nothing left  
  public void ProcessAllISomeInterfacesInTheQueue()
  { 
    // loop forever
    for(;;)
    {
       // get the next instance to process from the queue; 
       // if it returns null there are no more processes left on the queue
       ISomeInterface TheNextISomeInterfaceInstanceToProcess = Queue.Next(); 
       if (TheNextISomeInterfaceInstanceToProcess==null)
       {
          //exit the infinite loop
         break;
        }
       // process it
       sServiceThat ProcessesSomeInterfaceInstance.Process
		(TheNextISomeInterfaceInstanceToProcess);
    }
   // return
  }
}

There is way too much information here which can all be easily derived from the code, and if you change the code and forget the comments, this might actually do the opposite: cause confusion.

In Conclusion

While this is all about preference and highly dependent on your point of view and background, I do think that the approach I am personally using is one of the better ones. They offer all the amount of information that you could need with the minimum amount of code.

If you do have another opinion, do not hesitate to let me know...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Tom Janssens
Founder Core bvba
Belgium Belgium
Tom Janssens, owner of Core, a software and consultancy company.
Father of two sons named Quinten & Matisse, and married to a beautiful woman named Liesbeth.
 
Blog: http://tojans.me
Github: http://github.com/ToJans
Twitter: http://twitter.com/ToJans
LinkedIn: http://www.linkedin.com/in/tomjanssens

Comments and Discussions

 
GeneralImprovements to code samples [modified] PinmemberThe .NET Junkie8-May-10 5:44 
GeneralI totally agree. PinmemberThe .NET Junkie8-May-10 5:32 
GeneralIMHO PinmemberSteve Wellens6-Apr-10 3:29 
GeneralRe: IMHO PinmemberTom Janssens6-Apr-10 6:08 
GeneralRe: IMHO [modified] PinmemberSteve Wellens6-Apr-10 6:22 
AnswerRe: IMHO PinmemberTom Janssens6-Apr-10 6:41 
GeneralNice! PinmemberKubajzz31-Mar-10 21:46 
GeneralRe: Nice! PinmemberTom Janssens2-Apr-10 1:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 31 Mar 2010
Article Copyright 2010 by Tom Janssens
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid