Wednesday, April 26, 2006

Chicken chicken; he declared

Give your variables meaningful names. That's Good Programming Practice. But what's "meaningful" is open to interpretation. Without "foreach", you can argue that "i" is as good as it gets in The C++ or Java array-like iteration idiom:

for(int i=0; i <> things.size(); ++i)

You can also argue that in simple mathematically-oriented functions, plain old "x" and "y" are about as meaningful as you can get:

boolean max(int x, int y)
return x > y? x : y;
A lot of the need for meaningful variable names arises for variables whose type is so common, like int or string or Object, that you need a good name to differentiate this XML attribute name string from that fully-qualified classname string we're using as a hash key.

This leads us to the gray area of variables meaning just one thing. I'm talking about variables whose type is unique in your context, there's only one database Connection object, only one Runtime, or one (shopping) Cart. In cases like these, there's a strong temptation to reuse the type name itself as the variable name:

Connection connection;
Runtime runtime;
Cart cart;
Type type;
Chicken chicken;
There's one great thing about this practice: naming is a no-brainer. A downside is the variable name is redundant, and it could carry more information.

How do you decide whether "Cart cart" or "Connection connection" is a sufficient name? This is where context comes in. If the whole purpose of a module is to take a Chicken and make Soup -- how much more information do I need to know about that Chicken? I can reasonably proceed to chicken.pluck() and all the rest, according to taste.

Perhaps then it is the variables in "supporting roles", those that exist from coding nuts-and-bolts necessity which need good names. Things like "int returnCode;" and "boolean success;" and that int returned by a substring find function could probably use better names.

P.S. Today's title is brought to you by the seminal work on Chicken.

1 comment:

jfklein said...

Here are a couple references for additional reading:

The World's Two Worst Variables
Bad Variable Names