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.

2 thoughts on “var improves readability

  1. Mark Aurit

    Im not buying it. It wasnt that long along ago that c# “devs” dissed vb “programmers” because they could dim anything as anything, and that was roundly decried as one more proof that vb wasnt a real language. Now c# can do the same, and suddenly its a good programming practice “because it makes you think more”, and “its not about being lazy”. Use it if you want, but please dont be disingenuous.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s