Dirt - Sparks - Code

Self indulgent rambling. Minimal redeeming attributes.

HomeHome

Why 'var' is evil

Stu Pocknee
Stu Pocknee
tags coding

For anyone not of the programming persuasion, the keyword ‘var’ is a C# language construct used to initialize variables in a way that does not require the type of the variable to be explicitly defined. This is normal in dynamically (weakly) typed languages such as javascript but unusual in C# (which is a statically typed language). The use of ‘var’ to define a variable relies on implicit typing where the type of the variable is defined by the context of its implementation. It’s noteworthy that the variable itself remains statically (strongly) typed.

Despite the title, ‘var’ is not evil. It can be a very useful construct. The title is only a blatant attention whore concocted as a tongue-in-cheek response to one of my devs whose opinion differs.

I explicitly disallow the use of ‘var’ in company code. This is a conscious executive decision that relates to several of the maxims I follow when writing code.

In particular, these include:


					Specificity - say exactly what you mean
					Simplicity - use fewer of all the things
					Clarity - write code in a way that maximizes the readers ability to interpret it
					Singulation - do one thing at a time, particularly on the one line
					Economy - minimize TCO (total cost of ownership/operation)
					Uniformity - if there are three ways to do the same thing pick one, and forget the others exist
					

In certain situations, the use of ‘var’ can meet one or more of these maxims better than the use of explicit typing. It’s not interesting for me to go into these here. Google will help you with this.

I do actually use ‘var’ in one specific way quite regularly. Rather than typing out a long and convoluted type name (thanks Linq!) I will often just bash out ‘var’, and then let the IDE rename it for me. I like that a lot. The key thing to note is that I always rename it.

Suffice it to say, on balance, I consider the downsides of ‘var’ to outweigh the upsides.

I am a fairly liberal individual. What consenting adults do behind closed doors is not my business. If you want to use ‘var’ in your own projects at home, go your hardest. I couldn't care less. In my code, however, kindly desist.