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)
operateOn(things.get(i));
You can also argue that in simple mathematically-oriented functions, plain old "x" and "y" are about as meaningful as you can get:
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.
boolean max(int x, int y)
{
return x > y? x : y;
}
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:
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.
Connection connection;
Runtime runtime;
Cart cart;
Type type;
Chicken chicken;
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:
Here are a couple references for additional reading:
The World's Two Worst Variables
Bad Variable Names
Post a Comment