
214
CHAPTER 7
■ TRAITS AND TYPES AND GNARLY STUFF FOR ARCHITECTS
Poignantly Killing Bunnies: Dwemthy’s Stairs
Why the Lucky Stiff is one of the best and most clever programmers in the Ruby commu-
nity.
11
He wrote Why’s (Poignant) Guide to Ruby, a most excellent Ruby tutorial.
12
Why
introduces some of Ruby’s metaprogramming concepts in Dwemthy’s Array
13
in which a
rabbit battles an array of creatures. N8han
14
updated the example to work in Scala.
15
With
a tip of the hat to Why, a nod and a wink to N8han, and a huge thanks to Jorge Ortiz for
finding this example, I’m going to talk about how
Rabbit * Dwemthy.s.stairs will cause our
hero, our rabbit, to throw a bomb at Dwemthy’s stairs, thus casting the first salvo in the
battle against the monsters that reside there.
As a library producer, we want to write code that makes it super-simple for library
consumers to express their logic. Being able to define weapons like
trait Axe { this: Monster =>
def |^ = Weapon((me, it) => turn(me, it, me.weapon + 45))
}
and compose them into Monsters like
object ScubaArgentine extends Monster with Axe {
def life = 46
def strength = 35
def charisma = 91
def weapon = 2
}
means that our library consumers will focus on the business logic at hand and will be able
to write concise, powerful, flexible code that can be read even by those who are not hard-
core computer geeks.
The Immutable World
Our example will build the rabbit in the immutable world of Scala and use functions for
transformation rather than
method_missing magic that Why uses in his example. Our
object hierarchy contains
Creatures of which the Rabbit is a subclass and Monster is a
subclass. There are many instances of
Monster, including Dragon. Dwemthy’s stairs contains
seven
Monsters. In Why’s example, only Rabbit could fight any of the Monsters, but our
Monsters will be able to fight each other. We can see what happens when the Dragon uses
its tail:
11. http://whytheluckystiff.net/
12. http://poignantguide.net/ruby/chapter-1.html
13. http://poignantguide.net/dwemthy/
14. http://technically.us/code
15. http://technically.us/code/x/dwemthy_s-arrayhhhhhlist-in-scally
19897ch07.fm Page 214 Monday, April 20, 2009 4:36 PM