Reducing Redundant Calculations
https://softwareengineering.stackexchange.com/questions/371385
-
06-02-2021 - |
Question
I am experiencing a dilemma. Let me explain it with two functions:
# Takes vector.magnitude(), vector.x, vector.y and uses it somewhere
def func1(vector, {other parameters 1}):
pass
# Takes vector.magnitude(), vector.x, vector.y and uses it somewhere
def func2(vector, {other parameters 2}):
It is not uncommon that func2
is called right after func1
with the same vector
variable. There is a redundant calculation for the vector magnitude, as it is calculated twice. Should the vector magnitude instead be a separate function parameter? If not, what should be changed to alleviate this problem?
Solution
Calculating the vector magnitude should be a method of the vector
class. Then it can cache and reuse the result as necessary or advisable. Burdening higher-level logic with micro-decisions like this is bad for readability.
Licensed under: CC-BY-SA with attribution
Not affiliated with softwareengineering.stackexchange