debuggable

 
Contact Us
 

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.

Motivation

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.

Code Example

Before

function underHeavyLoad($database) {
   $numVisitors = $database->getNumberCurrentOnlineUsers();
   return ($numVisitors > 200);
}

After

function underHeavyLoad($database) {
    return ($database->getNumberCurrentOnlineUsers() > 200);
}

 
&nsbp;

You can skip to the end and add a comment.

Nate Klaiber said on Jun 11, 2007:

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.

Tim Koschuetzki said on Jun 11, 2007:

Correct Nate.

Check out my corresponding article for your advice.

Nate Klaiber said on Jun 11, 2007:

@TIm
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 :)

Tim Koschuetzki said on Jun 11, 2007:

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.