Saturday, April 28, 2007

temp

Programming peeve of the day: No one should ever use a variable named temp. The standard (but by no means only) context for this practice is the idiom for swapping the contents of two settable locations (variables, for instance):

let temp = loc1
in
(loc1 := loc2;
loc2 := temp)

in some hypothetical imperative language. Why temp? Why not prev_ptr_value? or pre_tax_profits? The usual rationale is that the variable has a short lifespan, so it's "temporary." Or perhaps that its value will be moving on shortly. If that makes any sense, we should adopt the same policy for all variables. We can give them names such as perm or likely_to_last, or perhaps valid_for_several_million_clock_cycles. If you think this is a step in the wrong direction, then the next time temp occurs to you as a fine name for a variable, spend a few extra seconds to find one that reminds the reader of your code what information is whizzing through your variable, not its expected flight time.

No comments: