Local Variables Reassigned Above Their Uses

Pattern: Local Variables Reassigned Above their Uses

...this pattern helps complete the SimplyUnderstoodCode pattern. This pattern helps solve the problem of making code understandable when you need to re-assign their values.

                                * * *

Sometimes a piece of code needs to re-assign local variables more than once. If this is done without paying attention to a person reading the code who is unfamiliar with it, misunderstandings are easy.

Sometimes a piece of code requires that a local variable have its value changed several times, perhaps in a loop. When this happens the problem is how to signal which use or reference of the variable goes with which assignment. In cases of complex control structure, there might be no way to have each reference or use correspond to exactly one assignment.

People normally read code from top to bottom, so their inclination is to recall the assignment that is textually above the reference or use.

Of course, if the code is complex, it will be difficult to understand and the code chunk ought to be well-documented other ways than by making the code plain, though it rarely hurts to do both.

Therefore, A local variable that must be re-assigned should be re-assigned in a place that is textually above where it is used or referenced.

                                * * *

Sometimes a local variable that is re-assigned could be turned into two variables where each assignment is actually a definition of a local variable, one inside the scope of the other. This is preferable to assigning twice. See pattern AssignVariablesOnce.


EditText of this page (last edited January 16, 1998) or FindPage with title or text search