13.07.2015 Views

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Reusing Temporary VariableTemporary Variable can be used to reuse the value of expressions that cannot be executed morethan once.How do you use an expression several places in a method when its value may change?Methods without temporary variables are easier to understand than methods with temporaryvariables. However, you sometimes encounter expressions whose values change, either because ofside-effects of evaluating the expression or because of outside effects, but you need to use the valuemore than once. Using a temporary variable is worth the cost in such a case, because the codesimply wouldn't work otherwise.For example, if you are reading from a stream, the evaluation of "stream next" causes the stream tochange. If you are matching the value read against a list of keywords, you must save the value.Thus:stream next = a ifTrue: [...].stream next = b ifTrue: [...].stream next = c ifTrue: [...]Is not likely what you mean. Instead, you need to save the value in a temporary variable so youonly execute "stream next" once.| token |token := stream next.token = a ifTrue: [...]...Resources that are affected by the outside world also require this treatment. For example, "TimemillisecondClockValue" cannot be executed more than once if you want to be guaranteed the sameanswer.Execute the expression once and set a temporary variable. Use the variable instead of theexpression in the remainder of the method.Role Suggesting Temporary Variable Name explains how to name the variable.<strong>Coding</strong> <strong>Patterns</strong> page 82 of 147 9/30/2006

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!