Introduce Explaining Variable

You have a complicated expression.

Put the result of the expression, or parts of the expression, in a temporary variable with a name that explains the purpose.

From page 124 of MartinFowler's excellent RefactoringImprovingTheDesignOfExistingCode: http://www.refactoring.com/catalog/introduceExplainingVariable.html


For example:

 if ( (x==0) || ((y<17) && name == null) ) {
   ..
 }
becomes:
 final boolean outOfActiveAreal = (x==0) || ((y<17) && name == null) ;
 if (outOfActiveAreal ) {
   ..
 }


Often, applying an ExtractMethod will make the code even clearer, while increasing the odds of a HappyCollision.


What's wrong with :

 // Out of Active Area
 if ( (x==0) || ((y<17) && name == null) ) {
   ..
 }
I believe it will run faster. The use of the temporary boolean variable - violates YagNi, while the use of a comment line does not. If you are looking at the source code instead of executing it, the comment might be useful, while running it you will not see it. The design of the code has not been improved by the introduction of a redundant variable, while its readability is improved, its functioning time has been increased.

A: Because PrematureOptimization is evil. The first example is Deoptimization, unless the code is repetitive. If it occurs OnceAndOnlyOnce, the commented code is optimal. If the test is required on a repeating basis, one would consider making it a function, not a temporary variable.

Who says the temporary variable makes it de-optimized? Have you compared the compiler-generated code for the two and conclusively demonstrated to a casual observer that the hand-optimized version will generate fewer and/or faster processor instructions than the temporary variable version? My experiences suggest that there will be no difference, particularly because the programmer has taken care to declare the temporary as final (or, more generally, used the corresponding keyword for whatever language). Compiling is fast and the machine will do it over and over again without complaint or loss of precision. A comment must be read, interpreted, and related to the code to which it applies by an imprecise, possibly tired or moody, human. At some point someone incurs the overhead of changing it to match code changes or someone else incurs the overhead of discovering the code has changed to make the comment false. --StevenNewton

See also: CommentCostsAndBenefits. The comment in the above example incurs only one of eight costs (Programmers ignore them) while accruing many of the benefits listed on CommentCostsAndBenefits.

 numCommentCosts = 1;
 // make sure comment worth it before adding it
 if (numCommentBenefits > numCommentCommentCosts)
 {
     // the sense of the test used to be reversed, but I can tell ONLY
     // because of the explaining variables.
     add_explaining_comment();
 }


[CategoryRefactoring]


EditText of this page (last edited August 2, 2004) or FindPage with title or text search