var improves readability

 

Countless times I’ve heard the argument that you should use the var keyword with caution, that it decreases readability of your code, or how it can be misused.

The example given in the linked post is:

    var Data = GetData(); 

 

According to the blog post, GetData returns a DataTable, something not inherently apparent. The problem however is due to the naming conventions used by the developer.

Firstly, GetData is a method indicating that it returns Data. The problem is, pretty much anything is Data. There has to be a more precise definition of what it is the method is actually doing. By this, I don’t mean you should necessarily rename the method to GetDataTable, since this doesn’t help. This just indicates what type it is returning, not what the method is doing. It would be an appropriate name if the domain of the problem were somehow about types, but in a business scenario, it doesn’t provide much value.

The second issue and just as important, is the variable name, data. Again, it is not descriptive enough. What is data? What kind of information does it hold? Is it a car? Is it many cars?

By using var, you are forcing yourself to think more about how you name methods and variables, instead of relying on the type system to improve readability, something that is more an implementation detail. Using the var keyword is not about being lazy, quite the contrary.


Posted 11-20-2009 8:12 AM by Hadi Hariri

[Advertisement]

Comments

Mattias Jakobsson wrote re: var improves readability
on 11-20-2009 2:55 AM

Completely agree with you here. Imo, if you need to declare the type to be able to read the code, you are doing something wrong.  After all, the important thing isn't the datatype it self but what methods and properties it contains, and visual studio will give you that anyway.

Imo var gives you advantages (such as easier refactoring), while it has no disadvantages.

Wouter Seye wrote re: var improves readability
on 11-20-2009 4:38 AM

Unless GetData returns <T>, then var is misused

Derik Whittaker wrote re: var improves readability
on 11-20-2009 6:23 AM

IMO we should remove Var and all left hand identifies.  WHO CARES WHAT TYPE IT IS.

If the object has the methods/properties/events i want, i really do not care what the 'type' is.

Awkward Coder wrote re: var improves readability
on 11-20-2009 6:28 AM

+1

Krzysztof Kozmic wrote re: var improves readability
on 11-20-2009 6:33 AM

@Derik,

well I'm not sure I'd go that far. It's not about caring what the type is. It's about being explicit you're creating a *new* local variable.

If you write just:

today = GetDateToday();

you might as well (mistakenly) reassign a variable that is already in scope.

It's dumb example, but I like this kind of explicitness in C#, same with being explicit about overriding method, which lead to many errors in C++.

This may lead to errors and programming mistates, whereas var can't.

Thomas Eyde wrote re: var improves readability
on 11-20-2009 7:38 AM

@Krzysztof

Or we could both get rid of explicit type declarations and disallow reassignments to an already (automatic) declared variable.

There are so few occasions where a reassignment is appropriate, so I could live with this restriction.

sean kearon wrote re: var improves readability
on 11-20-2009 10:33 AM

Definitely - var rules!

Thomas Weller wrote re: var improves readability
on 11-20-2009 9:56 PM

@Derik:

Every programmer who cares about the expressiveness and readabiltity of his code!

The 'var' keyword is nothing to use everywhere, but it should be used only to shorten long code lines, if the type is clear anyway...

@Thomas, Sean:

We already had this unsafe typing in conjunction with reassignments in VB up to v6. It led to glorious disasters, I even saw an entire 30-headed company going bancrupt because of it...

Hadi Hariri wrote re: var improves readability
on 11-21-2009 2:33 AM

@Thomas (Weller),

The whole point is about being more expressive.

Hadi Hariri wrote re: var improves readability
on 11-21-2009 2:34 AM

@Wouter,

And why is that?

sean kearon wrote re: var improves readability
on 11-21-2009 3:31 AM

@Thomas (Weller):

var is actually typed, it is different from the old VB style assignments that caused such problems.  More details here: msdn.microsoft.com/.../bb384061.aspx  

For me the whole point with var is that it helps you to write better code.  Code that may be readable (just) with explicit declarations is less so with implicit declarations.  Hadi's example is a good illustration.  By applying better names to the variable and the method value is added to the current line as well as subsequent uses of each part.  

Dennis Sellinger wrote re: var improves readability
on 11-21-2009 2:31 PM

When we first started with c# 3, I tended to avoid var.  I have come up with three indicators to help me in my choice  to use or not:

1. lifetime - variable is very short scope are easier to understand with var became the construction and use is localized.  For example, do you type your lambda?

2. variable with very long type names seem to be of types you don't care very much about.  This is especially true for short lived generic types.

3. We have a lot of conventional name (especially for short lived objects).  For example, when we create a StringBuilder we typically call it "sb".  I think in this case, the type just gets in the way.

Hadi Hariri wrote re: var improves readability
on 11-21-2009 3:16 PM

@Dennis,

In regard to point 3, why call it "sb"?

Devmentia wrote re: var improves readability
on 11-22-2009 6:39 AM

You should use the var keyword with caution, as you should use any keyword with caution. When you suggest that the var keyword in conjunciton with appropriate naming, you are applying your caution.

devmentia.blogspot.com/.../comment-or-dont-comment-var-or-no-var.html

Rob W wrote re: var improves readability
on 11-22-2009 6:45 AM

In my opinion "var" should only be used for anonymous types. This is exactly what is was introduced to support.

Using var everywhere for local variables makes code much harder to read at a glance. OK, the VS tooltips will tell you what the type is but that slows you down. You also can't use var for member/class scoped variables.

If you don't want to care about what type something is then you should consider using a dynamicly typed language such as (Iron)Ruby/Python.

Type is extremely important in understanding code. Take the following example:

var a = GetSomeValue();

Console.WriteLine(a+3);

Without the type I'm not sure what this bit of code is doing. If GetSomeValue() returns a string "foo" then this will print "foo3". If it returns an int 4 then it would be 7.

Hadi Hariri wrote re: var improves readability
on 11-22-2009 9:13 AM

@Rob,

your issue is you're naming your variable "a", not that you can't infer the type without a tool.

Hadi Hariri wrote re: var improves readability
on 11-22-2009 9:18 AM

@Devmentia,

Calling people "nutters" (per your blog post), doesn't really add much value to a discussion.

Devmentia wrote re: var improves readability
on 11-22-2009 11:46 AM

Do you think that I am calling you personally a nutter? In fact, I agree with your sentiment that the var keyword is acceptable. My previous comment to you was that you are indeed using the caution that people advise that you should. In your case, the caution is applied by using sensible naming. I included the link to my post because my post argues that the extremists (as I call them 'nutters') are incorrect, not you.

Unless I missed the point of your post and you are placing yourself amongst the people who suggest var should be used always. I don't think you are.

As for using the word nutters, I am happy with that. I could have said extremists, eccentrics or loonies quite as happily. Anyone who can argue an extreme point of view such as those I mention are, in my humble opinion, nutters.

Hadi Hariri wrote re: var improves readability
on 11-22-2009 2:20 PM

@Devmentia,

I am a very pragmatic person and far from purist or extremist. However, what I am saying in this post is that yes, I would always favor the usage of var because it forces you to think more about how you write your code.

Thomas Eyde wrote re: var improves readability
on 11-23-2009 6:26 AM

@Thomas Weller, I think you missed my point. I think reassignment is a code smell and should be disallowed. Once assigned, a variable should be fixed. If this restriction is in place, then it's perfectly safe to not declare variables before use.

@Rob W, really? Was var introduced only to support anonymous types? If that were the case, the compiler should have enforced it.

Devmentia wrote re: var improves readability
on 11-23-2009 7:50 AM

@Hadi.

I got the impression that you were pragmatic from your words. I also got the impression that you favour var. That's OK, it's a preference. I didn't think you were saying that you should only use var and stop using full type declarations. I hope you weren't because that is the type of view that my post is about.

The difference I saw was that your post appeared to be positive, arguing the case for your preference. Many posts are negative, simply arguing that a method is wrong and should never be used.

I am presuming that you are not really saying that you should use var and NEVER use type declarations. This would be a silly standpoint. For example, it would prevent you from using things like:

IMyDoobrie doobrie = new TextDoobrie();

ie. You would no longer be able to create a local based upon an interface.

Use only of var is a fallacious argument but one that I have heard (and seen written) on several occasions.

Hadi Hariri wrote re: var improves readability
on 11-23-2009 8:30 AM

@Devmentia,

I would say that "new TextDoobrie()" tightly couples you to a specific implementation anyway.

In regard to the other issue, I've not taken offense and I hope the feeling is mutualMy comment was more general. Let's just put it past us.

Terry wrote re: var improves readability
on 11-23-2009 12:33 PM

This article makes a faulty assumption that developers will recognize they have a poorly named variable because they use the "var" keyword in their programs and then rename it accordingly. This is just pixie dust logic I'm afraid. People who write unreadable and therefore often incorrect code aren't even aware of their own incompetency and will just plow ahead. At least with type information in place on declaration other programmers who have to maintain these monstrosities will have an easier time refactoring these messes. Did I mention that its likely that no comments or unit tests of any kind will be found in the code as far as the eye can see? *Sigh*

Hadi Hariri wrote re: var improves readability
on 11-23-2009 1:39 PM

@Terry,

Maybe instead of ploughing along, they can improve and others that have more experience can teach them.

The only assumption I make is that people are intelligent.

We should all strive to improve.

Devmentia wrote re: var improves readability
on 11-24-2009 8:13 AM

@Hadi

No offense meant, no offense taken :-)

That particular line of code would indeed tie you to an implementation. If it were part of a factory pattern / abstract factory then perhaps not. You see my meaning though.

Brad wrote re: var improves readability
on 12-02-2009 9:40 PM

Nice post, it's almost a summary of my rant last month.

For what it's worth: www.bradleyboveinis.com/.../e28098vare28099-as-an-Indicator-of-Clean-Code.aspx

Guilherme Cardoso wrote re: var improves readability
on 06-25-2010 1:23 PM

Hi Hadi,

Now i understand this quote: "Using the var keyword is not about being lazy, quite the contrary. "

I've never notice how important is variable name, but during the development of web apps, i've questioned my self "what it was the name of that method?". Using var is a good way to force us to give good names to variables and methods like you said.

Thanks for the recommendation of this article, really useful ;)

weblogs.pontonetpt.com/guilhermecardoso

geekswithblogs.net/guilhermecardoso

Fabulous Adventures In Coding wrote Uses and misuses of implicit typing
on 04-20-2011 1:38 PM

One of the most controversial features we've ever added was implicitly typed local variables , aka "var

Невероятные приключения в коде wrote Uses and misuses of implicit typing
on 05-09-2011 5:05 AM

Плюсы и минусы неявной типизации Одной из наиболее сомнительных возможностей, когда либо добавленных в язык, является объявление неявно типизированных локальных переменных , a.k.a «var». Даже сегодня, несколько лет спустя, я все еще нахожу статьи , в

backlinks service wrote re: var improves readability
on 01-17-2013 3:38 PM

gL9mJJ Really appreciate you sharing this blog article.Thanks Again. Much obliged.

buy viagra wrote re: var improves readability
on 02-02-2013 1:28 PM

q46KJs Fantastic blog article.Thanks Again. Will read on...

buy viagra online wrote re: var improves readability
on 02-02-2013 5:00 PM

knpNG6 Very good post.Much thanks again. Really Cool.

buy imitrex wrote re: var improves readability
on 02-13-2013 5:25 PM

T1Fryn I really like and appreciate your article.Thanks Again. Much obliged.

buy imitrex wrote re: var improves readability
on 02-15-2013 12:23 AM

izzD0q Looking forward to reading more. Great blog post. Really Cool.

buy cialis discount wrote re: var improves readability
on 02-24-2013 5:25 PM

9UkhrB I appreciate you sharing this article post.Much thanks again. Really Great.

clomiphene 25 mg wrote re: var improves readability
on 02-28-2013 3:27 AM

l29kR3 Im obliged for the post. Keep writing.

bookmaring service wrote re: var improves readability
on 03-13-2013 11:01 AM

fSG4yR I cannot thank you enough for the blog.Really looking forward to read more. Will read on...

bookmarks wrote re: var improves readability
on 03-13-2013 9:30 PM

Rs2I32 I am often to blogging and i really appreciate your content. The article has really peaks my interest. I am going to bookmark your site and keep checking for new information.

buy social bookmarks wrote re: var improves readability
on 03-23-2013 5:01 AM

YwjyQL Im obliged for the blog post.Really looking forward to read more. Will read on...

buy social bookmarks wrote re: var improves readability
on 04-03-2013 5:32 AM

RBJIeb Thank you ever so for you article post.Really looking forward to read more. Much obliged.

comedy channel wrote re: var improves readability
on 04-05-2013 1:22 PM

Thanks a lot for the blog post.Much thanks again. Really Cool.

social bookmarking service wrote re: var improves readability
on 04-07-2013 2:05 PM

eJXfwY Thanks again for the blog article.Much thanks again. Cool.

buy social bookmarks wrote re: var improves readability
on 04-12-2013 2:19 PM

PfcwoZ I truly appreciate this post.Much thanks again.

buy social bookmarks wrote re: var improves readability
on 04-13-2013 6:35 AM

haPdNV Thanks a lot for the blog article.Really thank you! Cool.

Social bookmarks wrote re: var improves readability
on 04-16-2013 3:40 AM

MyfiYe A round of applause for your article post.Much thanks again. Cool.

digital slr lenses wrote re: var improves readability
on 05-14-2013 7:54 AM

MidRxk A round of applause for your post.Much thanks again.

social bookmarking service wrote re: var improves readability
on 06-06-2013 10:48 PM

MFmxHe I loved your blog. Will read on...

cheap social bookmarks wrote re: var improves readability
on 06-19-2013 8:42 AM

u2Qd18 Major thankies for the blog.Really looking forward to read more. Much obliged.

cheap bookmarks wrote re: var improves readability
on 06-21-2013 8:57 AM

RD4sop Muchos Gracias for your article.Really thank you! Keep writing.

moldavian news wrote re: var improves readability
on 07-08-2013 11:28 AM

p18esm Thank you ever so for you article post.Much thanks again. Awesome.

super news wrote re: var improves readability
on 07-13-2013 7:11 AM

OepU7c I really like and appreciate your post.Really thank you!

best news of them all wrote re: var improves readability
on 08-04-2013 9:22 PM

hDHlWR Thanks so much for the article.Really looking forward to read more. Really Great.

link building team wrote re: var improves readability
on 10-01-2013 7:21 AM

s8ZcR4 Enjoyed every bit of your article post.Really looking forward to read more. Want more.

patrik wrote re: var improves readability
on 10-01-2013 5:16 PM
best link build wrote re: var improves readability
on 10-15-2013 3:16 PM

ytEoVL Awesome article post.Thanks Again. Will read on...

top seo guys wrote re: var improves readability
on 10-26-2013 2:30 PM

cIhfmq Im obliged for the article post.Really thank you! Want more.

look at this wrote re: var improves readability
on 01-15-2014 9:08 PM

LvMm3F Fantastic article post.Really looking forward to read more. Will read on...

awesome things! wrote re: var improves readability
on 01-20-2014 1:07 AM

idP3zg Im obliged for the blog.Really looking forward to read more. Great.

stunning seo guys wrote re: var improves readability
on 02-06-2014 5:10 PM

rhIjFa Really informative blog.Really thank you! Fantastic.

matt wrote re: var improves readability
on 04-09-2014 2:47 AM

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)