Click here to Skip to main content
15,867,488 members
Articles / Programming Languages / C#

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

Rate me:
Please Sign up or sign in to vote.
3.71/5 (5 votes)
31 Mar 2010CPOL3 min read 15.1K   2   8
"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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Virtual Sales Lab
Belgium Belgium

Comments and Discussions

 
GeneralImprovements to code samples [modified] Pin
The .NET Junkie8-May-10 5:44
The .NET Junkie8-May-10 5:44 
GeneralI totally agree. Pin
The .NET Junkie8-May-10 5:32
The .NET Junkie8-May-10 5:32 
GeneralIMHO Pin
Steve Wellens6-Apr-10 3:29
Steve Wellens6-Apr-10 3:29 
GeneralRe: IMHO Pin
Tom Janssens6-Apr-10 6:08
Tom Janssens6-Apr-10 6:08 
GeneralRe: IMHO [modified] Pin
Steve Wellens6-Apr-10 6:22
Steve Wellens6-Apr-10 6:22 
AnswerRe: IMHO Pin
Tom Janssens6-Apr-10 6:41
Tom Janssens6-Apr-10 6:41 
Ok, while I do understand what you mean, I think context might be helpful as well. Big Grin | :-D

My initial comment was a bit harsh *cough* understatement *cough*, and I probably should have waited a bit before posting an answer to your comment.
I would like to mention that I do appreciate the discussion; codeproject is a community site after all, and we are here to learn from each other.
IMHO it is good to question whether we are doing things the right way or not...

Anyway, happy coding/reading/writing/voting/commenting !!

GeneralNice! Pin
Kubajzz31-Mar-10 21:46
Kubajzz31-Mar-10 21:46 
GeneralRe: Nice! Pin
Tom Janssens2-Apr-10 1:41
Tom Janssens2-Apr-10 1:41 

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

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