Local variables are only accessible from their point of declaration to the end of their scope. Following the principle that information should spread as little as possible, declare local variables just before they are used and in the innermost possible scope.
There are a handful of common roles for local variables:
Collector: a variable that collects information for later use. Often the contents of collectors are returned as the value of a function. When a collector will be returned, name it result or results.
Count: a special collector that collects the count of some other objects.
Explaining: if you have a complicated expression, assigning bits of the expression to local variables can help readers navigate the complexity:
int left = …;
int height = …;
int bottom = …;
return new Rectangle(top, left, height, width);
While not computationally necessary, the explaining local variables help what would otherwise be a long, complicated expression.
Explaining locals are often a step towards helper methods. The expression becomes the body of the method, and the name of the local variable suggests a name for the method. Sometimes these helpers are introduced to simplify the calling method. Sometimes they help eliminate the duplication of common expressions.
Reuse: when an expression’s value changes but you need to use the same value more than once, store the value in a local variable. For example, if you need the same timestamp for several objects, you can’t fetch the time fresh for each object:
Instead, a reusing local variable freezes time for your purposes:
for (Clock each: getClocks())
Element: the final common use of local variables is to hold the elements of a collection that is being iterated. As in the example above, each is a clear, simple name for an element local variable. If I want to know “each what?” I can glance at the for statement above.
For nested loops, append the name of the collection to the element local name to distinguish them:
for (Source eachSender: getSenders())
for (Destination eachReceiver: getReceivers())
|This work is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported License|