Sunday, November 12, 2006

Pages 115-6: Instance Variables in Mixins


Listen to this article.

Value: High

Level: Average

Summary:
If a "mixin’s instance variables [...] clash with those of the host class or with those of other mixins [your] program will go wrong in unexpected ways". The author suggests to "ensure that the [mixin's] instance variables have unique names to distinguish them from any other mixins in the system".

An alternative solution could be to "use a module-level hash, indexed by the current object ID, to store instance-specific data without using Ruby instance variables".

Finally the author talks about method lookup, explaining that Ruby looks first in the class of the object, then in the mixins last included, first searched), then in the superclasses (and, of course, their mixins).

Memo:
Give unique names to mixins' instance variables and methods.

Example:

Wrong Code

module SexuallyAppealing
attr_accessor :score
end
class PokerPlayer
include SexuallyAppealing
def initialize(name, surname, score)
@name = name
@surname = surname
@score = score
end
end
player1 = PokerPlayer.new("Adolfo", "Persichetti", 3200)
player1.score = 1
puts player1.inspect

Right code

module SexuallyAppealing
attr_accessor :sex_score
end
class PokerPlayer
include SexuallyAppealing
def initialize(name, surname, score)
@name = name
@surname = surname
@score = score
end
end
player1 = PokerPlayer.new("Adolfo", "Persichetti", 3200)
player1.sex_score = 1
puts player1.inspect

Doubts: 0

Reported Errata (at 10/17/06 14:17:18 PDT): 4
  • #2324 is an useful tip: in the example code there are method calls calling an instance variable. Those method calls could be mistakenly interpreted as local variables from a newbie: the reporter suggests to use an instance variable instead of that method calls.
  • #1938, #2814 regard the deprecated Object#id: just use Object#object_id instead.
  • #1937 is a typo.

Errata I found: 1
  • A typo on page 116: "Abmiguous" instead of "Ambiguous".

My suggestions to the author: 2
  • Give an example when stating that "mixin modules don't [usually] try to carry their own instance data around [but] use accessors to retrieve data from the client object".
  • Specify that "State", described as "a module-level hash" is a module constant.

0 Comments:

Post a Comment

<< Home