Lab Notes

Things I want to remember how to do.

Io Gotcha

September 22, 2012

As you are probably aware, I am working my way through Seven Languages in Seven Days by Bruce Tate. (And if you have ever googled basic questions on the Io language, you will know that I am not the first person to have this idea.) In any case, I am on Day of Io, but before I get to anything specific there, I wanted to share a gotcha of Io that I encountered.

Coming from an object-oriented background (like Java) you might find yourself writing code like the following:

Gotcha := Object clone do(
conspirators ::= list()

conspire := method(c,
conspirators push(c)
return self
)
)

walter := Gotcha clone
walter conspire("jesse")
("walter: " .. walter conspirators) println

gus := Gotcha clone
gus conspire("mike")
gus conspire("victor")

("walter: " .. walter conspirators) println
(" gus: " .. gus conspirators) println

Everything seems fine, we initialize a list and then start adding elements to it. But here is the output:

walter: list(jesse)
walter: list(jesse, mike, victor)
gus: list(jesse, mike, victor)

Somehow in the process of creating gus and adding his conspirators has caused the list of conspirators for walt to grow. What is happening here is that conspirators is a slot on Gotcha that is never overridden by the clones walt and gus. So they are all sharing the same conspirator list. (Fans of Breaking Bad will realize that this situation cannot be allowed!)

The solution (well, one solution, there are probably others) is to use the init method to set the conspirators slot:

Fixed := Object clone do(
conspirators ::= nil

init := method(
setConspirators(list())
)

conspire := method(c,
conspirators push(c)
return self
)
)

walter := Fixed clone
walter conspire("jesse")
("walter: " .. walter conspirators) println

gus := Fixed clone
gus conspire("mike")
gus conspire("victor")

("walter: " .. walter conspirators) println
(" gus: " .. gus conspirators) println

Now walt and gus maintain a separate list of conspirators (as Vince Gilligan intended):

walter: list(jesse)
walter: list(jesse)
gus: list(mike, victor)

If you find yourself making these kinds of gaffes, re-read the Io style guide at http://en.wikibooks.org/wiki/Io_Programming/Io_Style_Guide.