Composing Methods: Inline Temp

Posted by Tim Koschützki, on Jun 11, 2007 - in Coding Techniques & Tools » Refactoring

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

php
  1. function underHeavyLoad($database) {
  2.    $numVisitors = $database->getNumberCurrentOnlineUsers();
  3.    return ($numVisitors > 200);
  4. }

After

php
  1. function underHeavyLoad($database) {
  2.     return ($database->getNumberCurrentOnlineUsers() > 200);
  3. }