Oct 22, 2009

Random Nerd Debates : Episode 2 VAR

In the second episode of Random Nerd debates we are doing to discuss the use of the C# keyword var.

First, what is var? MSDN has a very succinct explanation of the keyword:

“Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.”

And the simple code example:

var i = 10; // implicitly typed
int i = 10; //explicitly typed


Ok so now that we are both on the same page let’s talk about usage of this keyword. I have a very specific rule when it comes to the usage of var.



I will only use the var keyword to shorten my code without obscuring the clarity. This means I will only use the var keyword if the type can be inferred directly by viewing the right side of the operation. By “directly” I mean that the type is explicitly specified in the right side of the operation. I don’t want to have to jump to the method declaration or hover over the expression to determine the type. The best way to show this is through code examples:



//Since foo is clearly specified on the right side I WILL use var in this case
var foo = new Foo();

//Since the return type of the method GetBar() is not clear I WILL NOT use var in this case
var bar = GetBar();

//Other places where I WILL use var
var foo = (Foo)bar;
var bar = foo as Bar;


The benefit of the var keyword is allowing to write more succinct code. To me, succinctness can not come at the cost of clarity. In my examples above where I WILL use var I don’t feel like I am sacrificing any clarity but I am reducing noise.



There are two exceptions to my rule. When writing a LINQ query you almost always see the use of var and so I will follow that convention



var files = from file in enumerableFiles
select new Uri(file.FullName,UriKind.Absolute);


The other exception is similar to the LINQ example but more specific. There are cases which I want to deliberately de-emphasize the underlying storage mechanism and keep it ambiguous. In these cases I will use var to purposely obscure the underlying type. Eric Lippert explained this idea well in a blog post. The tidbit from Lippert was this:



   “Another subtle point here: notice how when I changed the type of the variable "racks" from "array of string" to "set of string", I didn't have to redundantly change the type thanks to implicit typing of local variables. I want to emphasize the semantics here, not the storage mechanism. If I felt that communicating the storage mechanism was an important part of this code -- because it has such a strong effect on performance -- perhaps I would choose to emphasize the storage by eschewing the "var"."



If you don’t already follow Eric’s blog I highly recommend it.



So I pose the question to you? Do you use var? Do you have a specific rule you follow when it comes to using it? Did you read this whole post and realize you just wasted the last 20 minutes of your life?

Labels: ,

Sep 9, 2009

Random nerd debates

Working as an engineer means that you get involved in random nerd debates on (at least) a weekly basis.

Most of these debates are useless drivel that aren’t worth noting but occasionally a topic comes up that is worth some level of posterity. Since my blog is otherwise full of useless stuff I figure starting a series on nerd debates isn’t the worst thing I could do :) 

So episode 1 of the Random nerd debate series.

(Interestingly you will notice that SyntaxHighlighter doesn’t even understand the Class name syntax Boolean, but does understand the alias syntax)

bool


Vs.



Boolean


Or int Vs. Int32 or whatever you want to call it. I am pretty sure I am in the minority here but I tend to prefer using the class name syntax Boolean Vs. the alias syntax bool. It is mostly personal preference but I think there are two key areas where the distinction makes a difference.



First when you are calling static methods that live on the class it seems weird to me to use the alias syntax.



bool.TryParse()


doesn’t feel the same as



Boolean.TryParse()


Again, I think I am in the minority here. My thought is that when you are calling methods you are doing so on the class itself. Using the alias just adds a level of indirection, albeit a minor and mostly overlooked one.



The second place where I think class name syntax gives you a true benefit is in clarity. When using the alias syntax int I have heard several people think that Int32 is simply a implementation detail and that the alias int hides that from you. So if you were compiling on x64 int would translate into Int64 instead of Int32.



This is a misconception however the int alias is simply that, an alias, or syntactic sugar for Int32. If you want Int64 you have to use the alias long. Of course you could specify Int64 explicitly using class name syntax and be done with it.



The more 64 bit programming becomes the norm I think the more we will run into some confusion. Do you use int, or double, or float, or long etc…



Interestingly the alias double maps to the class Double but the alias float maps to the class Single (have you ever seen someone use Single in their code?) In a chat with a friend about this topic his response was



“I go with shorter just from habit, but would generally defer to the team standard. i.e. it's not an issue I feel strongly about, but do feel that a decision one way or another needs to be made on a project”



Generally I agree with that statement and I think team level consistency is important. I think in most cases you will see teams using the alias and I think, in most case, this works out fine for them. All programmers can read the alias and I think that some may even be confused at first if they see the ClassName syntax and haven’t seen it before but, to me, it increases clarity and intent.



Stack Overflow had a nice thread about this very thing that I found while poking around for this post



You can find a complete list of all the built in type aliases for .NET, and their equivalent class name here



In a bit of a contradiction of style I do however use the var keyword very often. Which may sound like it reduces code clarity but there are places in which I purposely want to abstract the implementation details of the backing type from my code. But that debate is for episode 2. Stay tuned.

Labels: , ,