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.

Searching LiteralHow do you search for one a few literal objects known when you write the code?If <strong>Smalltalk</strong> had a case statement, you would be tempted to writeCharacter>>isVowelcase self asLowercase of$a:$e:$i:$o:$u: ^trueotherwise: ^false(I’m suggesting case statement syntax. A Choosing Message is almost always better than hardcoded cases, anyway.)Since <strong>Smalltalk</strong> doesn’t have a case statement, you generally have to resort to Boolean orconditional logic:Character>>isVowel| lower |lower := self asLowercase.^lower = $a | (lower = $e) | (lower = $i) | (lower = $o) | (lower = $u)Pretty ugly, eh? Not as bad as:Character>>isVowelself = $a | (self = $A) ifTrue: [^true].self = $e | (self = $E) ifTrue: [^true].self = $i | (self = $I) ifTrue: [^true].self = $o | (self = $O) ifTrue: [^true].self = $u | (self = $U) ifTrue: [^true].^falseBecause Strings are literals, you can use the collection protocol to implement the same thing muchmore compactly:Character>>isVowel^’aeiou’ includes: self asLowercaseYou can do the same thing with Symbols:Style>>isFancy: aSymbol^#(bold italic) includes: aSymbolThis is not a trick that comes up every day, but used occasionally it can save you a few lines ofcode.Ask a literal collection if it includes the element you are looking for.<strong>Coding</strong> <strong>Patterns</strong> page 117 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!