I will further add to Alexander's well-explained answer. As he mentioned, 9/10 times we can use this refactoring strategy. I will add where not to apply this
1. If you have a database query operation involved 2. if you are reading from a file 3. if anything involves with complexity greater than or equal to O(n^2)
Also, I think it is possible to calculate it once and store it as a class variable instead of a local variable.
I had the same query, and I understand now.
I will further add to Alexander's well-explained answer. As he mentioned, 9/10 times we can use this refactoring strategy. I will add where not to apply this
1. If you have a database query operation involved
2. if you are reading from a file
3. if anything involves with complexity greater than or equal to O(n^2)
Also, I think it is possible to calculate it once and store it as a class variable instead of a local variable.