tl:dr how does decoupling work? could need some little example
I'm reading Programming Ruby - The Pragmatic Programmer's Guide. (http://ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html)
There is an example on how to implement to_s for subclass KaraokeSong of Song.
class KaraokeSong < Song
# ...
def to_s
"KS: #{@name}--#{@artist} (#{@duration}) [#{@lyrics}]"
end
end
aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")
aSong.to_s » "KS: My Way--Sinatra (225) [And now, the...]"
Now they say its a bad way to do it:
Say we decided to change Song to store the duration in milliseconds. Suddenly, KaraokeSong would start reporting ridiculous values. The idea of a karaoke version of ``My Way'' that lasts for 3750 minutes is just too frightening to consider.
Instead you should define to_s with super:
def to_s
super + " [#{@lyrics}]"
end
Now when the @duration variable still stores the song duration in miliseconds, how does the new to_s which just calls the parent's method solve the problem? It still returns 3750 minutes, doesn't it?
I think i dont really understand the difference between those 2.
It's assumed that Song
will take care of the proper output of its @duration
.
And if we will decide to change Song
to store the duration in milliseconds, we will just change Song#to_s
method and won't have to change to_s
of all its descendants.