...this pattern helps complete the SimplyUnderstoodCode pattern. This pattern helps solve the problem of relating a use or reference to a variable to the place where its value is assigned.
* * *If a variable is assigned twice, you might have trouble figuring out which assignment provides the value at a particular use place, and your inclination is to remember the last assignment you looked at. This could lead to misunderstanding and incorrect changes to a program.
Local variable names are frequently chosen to remind the code reader of the purpose of the variable. Sometimes the quantity that a local variable represents will change, and there will be a need to reassign the variable.
But, suppose someone is reading that chunk of code later on and sees a reference or use of the variable. If the variable has been assigned in two places, the person will have trouble figuring out which assignment is the one that the use will see. This problem is made worse if there is a complicated control structure and the code reader is not scanning the code in the order of control flow. The natural thing to do is to remember the assignment you most recently saw. If the code's control flow is top-to-bottom and you are reading top to bottom, there is less of a problem, but confusion is still possible. And, the more complex the code fragment - the more re-reading is necessary - the more likely the wrong assignment will be associated with the use or reference.
Furthermore, the problem is made worse if the assignments and the uses are not on the same page or screen.
Therefore, Assign local variables only once, and, if possible, do that at the place where the local variable is defined. Make sure these places all fit on one page or screen. If you need to reassign a local variable, try to make a new local variable with the same name and arrange for the chunk of code containing its definition (and only assignment) and its use to fit on one page or screen.
* * *This pattern is related to LocalVariablesDefinedAndUsedOnOnePage, LocalVariablesReassignedAboveTheirUses, MakeLoopsApparent, BuildLoopsYourself, and FunctionsForLoops.
This page mirrored in WikiPagesAboutRefactoring as of April 29, 2006