Composing Methods: Inline Temp
Posted on 11/6/07 by Tim Koschützki
You have a temporary variable that is created with a simple expression. Now the temp is getting into the way of other refactorings. Replace all references to the temporary variable with the expression.
Often you will find yourself having temporary variables that carry the contents of simple method calls. A good thing is to remove the temporary variables and replace all references with the method or function invoked. This leads to much clearer code, as the method or function name ideally speaks for itself already, and saves you one code line. The less code the better!
Also, often you can use Inline Temp when you are having too many temporary variables around so that extracting functionality into their own methods (called Extract Method) becomes difficult. An article about Extract Method will be written later.
Beware of using Inline Temp in connection with loops as this can sometimes cause disastrious performance issues. Check Optimising Loops for further information about that.
$numVisitors = $database->getNumberCurrentOnlineUsers();
return ($numVisitors > 200);
return ($database->getNumberCurrentOnlineUsers() > 200);
You can skip to the end and add a comment.
Check out my corresponding article for your advice.
Sorry about that, I didn't realize you had another article on here related to that topic. I am just starting to check out the rest of your site, but hadn't stumbled upon that. Feel free to delete my comments if necessary :)
Nah I won't delete any comments unless they are spam. :) In fact I agree with you and should have linked that other article in this one, too.
I am doing that right now. ;)
[...] the local-variable checks: See if Inline Temp or Replace Temp With Query make sense. If one variable is modified, you can most often treat the [...]
This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.
I think this is good advice. The only instance I would recommend against using the expression versus variable is with loops. For instance, instead of using a for loop with the expression 'count($variable)', it would be better to have $num = count($variable) before the function and then compare to the $num variable. This way the function doesn't need to run with each iteration of the loop.
So, I agree - but I think it still takes some discretion as to where to do this.