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.

Explicit InitializationYou’ve found Common State that always starts at the same value. A Creation Parameter Methodhas just set the state of some variables.How do you initialize instance variables to their default value?Usually in these patterns I have tried to avoid ambiguity. If there are two equally valid ways toaccomplish some task, I pick one.Initialization is an issue for which I cannot in good conscience pick one solution. There are twoways to solve the problem of instance variable initialization, each valid in different circumstances,and those circumstances you are certain to encounter.This pattern emphasizes readability over flexibility. You should use an initialize method when youwant people to read your code as easily as possible, and you aren’t terribly concerned about futuresubclasses. By putting all the initialization in one place, Explicit Initialization makes it easy tofigure out what all the variables are.Flexibility is impaired by Explicit Initialization because all of the variables are mentioned in asingle method. If you add or remove an instance variable, you will have to remember to edit theExplicit Initialization.Explicit Initialization can also be more costly than Lazy Initialization Methods because they spendthe effort to initialize all the values at instance creation time. If computing some of the initialvalues is expensive and the values aren’t used right away (or perhaps not at all), you may be able toimprove performance by not initializing them right away.Implement a method “initialize” that sets all the values explicitly. Override the class messagenew to invoke it on new instances.For example, consider a Timer that defaults to executing every 1000 milliseconds. It also keepstrack of how many times it has gone off:Class: Timersuperclass: Objectinstance variables: period countUse basicNew to create the instance to avoid accidentally setting “initialize” off twice should afuture superclass invoke it.Timer class>>new^self basicNew initializeNow we can initialize the values:Timer>>initializecount := 0.period := 1000Even better, we can explain that magic number 1000 with a message:<strong>Coding</strong> <strong>Patterns</strong> page 63 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!