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.

StackHow do you implement a stack?One of the first objects many people write when they come to <strong>Smalltalk</strong> is Stack. Stack is the basicdata structure, fabled in song, story, and hundreds of papers about theoretical programminglanguages.Algorithms that use stacks can be simply expressed in <strong>Smalltalk</strong>. The syntax lends itself to readablecode written in terms of pushes and pops. However, there is no Stack class in any of the basicimages. I’ve seen one written any number of times, but they never seem to last long. <strong>Smalltalk</strong>programmers need stacks, too. What do they do?It’s easy to simulate a stack using OrderedCollection:Stack OperationpushpoptopdepthemptyOrderedCollection messageaddLast:removeLast:lastsizeisEmptyThe result doesn’t read exactly like a stack would read, but the idiom is so recognizable that thecost of using the idiom is far less than the cost of adding a new class to the image.Why doesn’t this result in confusing code? Why don’t you write part of the algorithm using anOrderedCollection as a stack, then forget and start using it as a queue?If there is a part of the algorithm that is complicated, you make a method or an object that gives it asimple public face. When you ask of the result “How many methods know this OrderedCollectionis really a stack?”, the answer is typically one. You use a Role Suggesting Temporary Variablename to communicate that the OrderedCollection is being used as a stack. End of story.Why is there no Stack in <strong>Smalltalk</strong>? Well, “just because”. It is part of the culture to simulate stacksusing OrderedCollection. If that’s how everybody does it, and it doesn’t cost you anything, that’show you do it, too.Implement a Stack using an OrderedCollection.You may need Composed Method to simplify code using OrderedCollections as Stacks so theidiom is not confusing.<strong>Coding</strong> <strong>Patterns</strong> page 114 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!