Let us suppose that you’re going to compute some value, and then send it to another function. Which snippet is better (using lhs
as shorthand for a variable identifier and rhs()
as shorthand for the right-hand side expression)?
lhs = rhs() do_work(lhs)
do_work(rhs())
My short answer isĀ it depends. Here is my informal set of heuristics:
-
- Is a type-cast involved (e.g., in a statically typed language like C)? If so, assign it to a variable.
- Would the variable name be a meaningful one that would provide non-obvious information about the nature of the computation? If so, assign it to a variable. For instance, if a long right-hand side expression computes perplexity,
ppl = ...
orperplex = ...
is about as useful as an inline comment. - Is the computation used again in the same scope? If so, assign it to a variable.
- Is the right-hand side just a very complicated expression? If so, consider assigning it to a variable, and try to give it an informative name.
- Otherwise, do not assign it to a variable.