I recently started working as a programmer and I am currently going through some codes (in C#) written by my colleagues. I have noticed that they tend to include logic within function calls within some conditional statements. For example:
if (MoveSpace(currentPos, distance * time))
{ doSomething }
They would also include logic when determining array positions. For example:
Space currentSpace = array[a*b, x*y]
Is this a good/bad practice? Would it be better if I create a new variable for these logic results and pass in the variable instead? Thank you.
1 Answer 1
The compiler will usually emit the same code no matter whether you extract subexpressions to local variables or not. Therefore, the principal goal in such decisions must be to increase readability for human readers of the code.
Now, temp variables with meaningful names can increase readability. It's probably better to use a temp variable called clip_duration
than an expression like tape_length / read_head_traverse_speed
even though both have the same meaning.
But additional lines can also decrease readability. The example above was a somewhat unintuitive calculation; for something like height * width
it might actually be better to use an inline expression rather than extract it into a temp variable called area
.
Therefore, as in many cases, the answer is "it depends". The parameters on which it depends in this case are: How easy is it to understand the ancillary calculation you are making? Is it simple enough that extracting it would just be repeating the obvious? If so, don't be afraid of nested expressions. If it isn't, choosing a good temp variable name goes a long way to making the code readable without having to add explanatory comments (which should generally be a last resort).
-
I just like to add that these temporary values should not be variables in most cases. They get a value assigned where they are declared and this value is not supposed to change. It makes sense to express this in your code if your language can do that. For example in Javascript use
const
rather thanvar
orlet
.Frank Puffer– Frank Puffer2019年01月16日 16:13:46 +00:00Commented Jan 16, 2019 at 16:13