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...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Lazy InitializationYou are initializing Common State.How do you initialize an instance variable to its default value?Here is the flip side of variable initialization. All the strengths of Explicit Initialization becomeweaknesses and all the weaknesses strengths.Lazy Initialization breaks initialization into two methods per variable. The first is a Getting Methodthat hides the fact that the variable is lazily initialized from anyone wanting to use its value. Thisimplies that there can be no Direct Variable Access. The second method, the Default ValueMethod, provides the default value of the variable.This is where the flexibility comes in. If you make a subclass, you can change the default value byoverriding the Default Value Method.Readability suffers because there isn’t any one place you can look to see all the variables and theirinitial values. Instead, you have to look at several methods to see all the values.Performance is another reason to use a Lazy Initialization. Expensive initialization that may not beneeded for a while (or at all) can be deferred by using Lazy Initialization.Writing a Getting Method for the variable. Initialize it if necessary with a Default ValueMethod.The Timer example from above needs no explicit initialization. Instead, count is initialized in itsGetting Method:Timer>>countcount isNil ifTrue: [count := defaultCount].^countAnd the default value comes from its own method:Timer>>defaultCount^0Similarly for period:Timer>>periodperiod isNil ifTrue: [period := self defaultPeriod].^periodTimer>>defaultPeriod^1000Some people swear by Lazy Initialization. They go so far as to say that all initialization should bedone this way. I actually lean towards Explicit Initialization. Too many times I’ve bent overbackwards to supply lots of flexibility that is never used. I’d rather do it the simple way first, thenfix it if it’s a problem. However, if I know I am writing code that is likely to be subclassed byothers, I’ll go ahead and Lazy Initialization from the first.A Default Value Method supplies a default value. A Compute Method supplies the value of anCaching Instance Variable.<strong>Coding</strong> <strong>Patterns</strong> page 65 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!