Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
31 Mar 2010 1  
Var keyword is for JavaScript - about using the var keyword & other coding guidelines

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:

C#
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.:

C#
var sl = new SimpleServiceLocator();

is not really more obvious than:

C#
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.:

C#
var x = SomeFunction(y,z); 

This is considered bad practice by most.

This one is not:

C#
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:

C#
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:

C#
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:

C#
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:

C#
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):

C#
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here