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.

Parsing StreamHow do you write a simple parser?You will probably have to write simple parsers in <strong>Smalltalk</strong>. I don’t mean the kind that computerscientists love, with lots of L’s and R’s and numbers in their name. I mean the simple kind, whereeach line has a keyword and then a bunch of information, different depending on the keyword.One simple way to structure code like this is by grabbing a line at a time and parsing it.parse: aStream[aStream atEnd] whileFalse: [self parseLine: aStream nextLine]parseLine: aString| reader |reader := ReadStream on: aString.keyword := reader nextWord.keyword = ‘one’ ifTrue: [self parseOne: reader].keyword = ‘two’ ifTrue: [self parseTwo: reader]....This leads to code that allocates Strings and Streams all over the place. Something (a String orStream) has to be passed to each method. If the methods are deeply nested, that extra parameterbecomes tedious. It is error-prone, too, since it is easy to forget whether you are dealing with aString or a Stream.In many cases, having many methods share the same instance variable is dangerous, especially if itis an object that will be side effected by many methods. A change in one method is likely affectother inadvertently. In the case of parsing, though, the danger is minimized because of simplenature of the control flow.Put the Stream in an instance variable. Have all parsing methods work from the sameStream.Using this pattern, the code above looks like:parse: aStreamreader := aStream. “Reader is now an instance variable.”[reader atEnd] whileFalse: [self parseLine]parseLinekeyword := reader nextWord.keyword = ‘one’ ifTrue: [self parseOne].keyword = ‘two’ ifTrue: [self parseTwo]....The lack of parameters cleans up the code considerably. Each parsing method has to be careful toleave the Parsing Stream in a known state so the other methods can simply assume where they arein the String.<strong>Coding</strong> <strong>Patterns</strong> page 120 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!