These attribute accessing methods do not have to be just simple
wrappers around an object's instance variables. For example, you might
want to access the duration in minutes and fractions of a minute,
rather than in seconds as we've been doing.
class Song
|
def durationInMinutes
|
@duration/60.0 # force floating point
|
end
|
def durationInMinutes=(value)
|
@duration = (value*60).to_i
|
end
|
end
|
aSong = Song.new("Bicylops", "Fleck", 260)
|
aSong.durationInMinutes
|
� |
4.333333333
|
aSong.durationInMinutes = 4.2
|
aSong.duration
|
� |
252
|
Here we've used attribute methods to create a virtual instance
variable. To the outside world,
durationInMinutes
seems to be an
attribute like any other. Internally, though, there is no
corresponding instance variable.
This is more than a curiosity. In his landmark book
Object-Oriented Software Construction ,
Bertrand Meyer
calls this the
Uniform Access Principle.
By hiding the
difference between instance variables and calculated values, you are
shielding the rest of the world from the implementation of your class.
You're free to change how things work in the future without impacting
the millions of lines of code that use your class. This is a big win.