Twitter LinkedIn Github



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.