Liskov Substitution Principle and the Ruby Core Libraries 78
There is a spirited discussion happening now on the ruby-talk list called Oppinions on RCR for dup on immutable classes (sic).
In the core Ruby classes, the Kernel
module, which is the root of everything, even Object
, defines a method called dup
, for duplicating objects. (There is also a clone
method with slightly different behavior that I won’t discuss here.)
The problem is that some derived core classes throw an exception when dup
is called.
NilClass, FalseClass, TrueClass, Fixnum,
and Symbol
) that do this. Consider, for example, the following irb session:
irb 1:0> 5.respond_to? :dup => true irb 2:0> 5.dup TypeError: can't dup Fixnum from (irb):1:in `dup' from (irb):1 irb 3:0>If you don’t know Ruby, the first line asks the
Fixnum
object 5
if it responds to the method dup
(with the name expressed as a symbol, hence the ”:”). The answer is true, becuase this method is defined by the module Kernel
, which is included by the top-level class Object
, an ancestor of Fixnum
.
However, when you actually call dup
on 5
, it raises TypeError
, as shown.
So, this looks like a classic Liskov Substitution Principle violation. The term for this code smell is Refused Bequest (e.g., see here) and it’s typically fixed with the refactoring Replace Inheritance with Delegation.
The email thread is about a proposal to change the library in one of several possible ways. One possibility is to remove dup
from the immutable classes. This would eliminate the unexpected behavior in the example above, since 5.respond_to?(:dup)
would return false, but it would still be an LSP violation, specifically it would still have the Refused Bequest smell.
One scenario where the current behavior causes problems is doing a deep copy of an arbitrary object graph. For immutable objects, you would normally just want dup
to return the same object. It’s immutable, right? Well, not exactly, since you can re-open classes and even objects to add and remove methods in Ruby (there are some limitations for the immutables…). So, if you thought you actually duplicated something and started messing with its methods, you would be surprised to find the original was “also” modified.
So, how serious is this LSP issue (one of several)? When I pointed out the problem in the discussion, one respondent, Robert Dober, said the following (edited slightly):
I would say that LSP does not apply here simply because in Ruby we do not have that kind of contract. In order to apply LSP we need to say at a point we have an object of class Base
, for example. (let the gods forgive me that I use Java)
void aMethod(final Base b){ .... }and we expect this to work whenever we call aMethod with an object that is a Base. Anyway the compiler would not really allow otherwise.
SubClass sc; // subclassing Base od course aMethod( sc ); // this is expected to work (from the type POV).
Such things just do not exist in Ruby, I believe that Ruby has explained something to me:
- OO Languages are Class oriented languages
- Dynamic Languages are Object oriented languages.
Replace Class with Type and you see what I mean.
This is all very much IMHO of course but I feel that the Ruby community has made me evolve a lot away from “Class oriented”.
He’s wrong that the compiler protects you in Java; you can still throw exceptions, etc. The JDK Collection classes have Refused Bequests. Besides that, however, he makes some interesting points.
As a long-time Java programmer, I’m instinctively uncomfortable with LSP violations. Yet, the Ruby API is very nice to work with, so maybe a little LSP violation isn’t so bad?
As Robert says, we approach our designs differently in dynamic vs. static languages. In Ruby, you almost never use the is_a?
and kind_of?
methods to check for type. Instead, you follow the duck typing philosophy (“If it acts like a duck, it must be a duck”); you rely on respond_to?
to decide if an object does what you want.
In the case of dup
for the immutable classes, I would prefer that they not implement the method, rather than throw an exception. However, that would still violate LSP.
So, can we still satisfy LSP and also have rich base classes and modules?
There are many examples of traits that one object might or should support, but not another. (Those of you Java programmers might ask yourself why all objects support toString
, for example. Why not also toXML
...?)
Coming from an AOP background, I would rather see an architecture where dup
is added only to those classes and modules that can support it. It shouldn’t be part of the standard “signature” of Kernel
, but it should be present when code actually needs it.
Kernel
, Module
, and Object
should be refactored into smaller pieces and programmers should declaratively mixin the traits they need. Imagine something like the following:
irb 1:0> my_obj.respond_to? :dup => false irb 2:0> include 'DupableTrait' irb 2:0> my_obj.respond_to? :dup => true irb 4:0> def dup_if_possible items irb 5:1> items.map {|item| item.respond_to?(:dup) ? item.dup : item} irb 6:1> end ...In other words,
Kernel
no longer “exposes the dup
abstraction”, by default, but the DupableTrait
module “magically” adds dup
to all the classes that can support it. This way, we preserve LSP, streamline the core classes and modules (SRP and ISP anyone?), yet we have the flexibility we need, on demand.
Trackbacks
Use the following link to trackback from your own site:
http://blog.objectmentor.com/articles/trackback/188
One odd thing about LSP: it is usually stated in terms of ‘types’ but people take that to mean ‘classes’, and generally that works well in statically typed languages.
The thing in dynamically typed languages is that we can have a notion of type which is independent of class. I can’t recall the example, but I remember hearing that most Smalltalk implementations have some things that look like glaring LSP violations if you are looking at classes rather than some general notion of type.
From what I’ve read, Tom Love, back in the 80s, came up with an interesting notion for dynamically typed systems that seems to do what LSP does for us.. he said that in a system, every method name should mean the same thing to every caller—if you have a ‘draw’ method you have to decide whether it draws a gun out of a holster or draws a representation on some medium. ‘Draw’ should mean the same thing to everybody.
I think the key thing is that in statically typed languages, the hierarchy bears the burden of communicating substitutability information. In dynamically typed languages you can get substitution easily and that pushes people toward looking beyond the hierarchy.
I don’t know. Maybe Ruby modules make a strict mapping of type to class possible.
I googled for references to Tom Love’s writings and I discovered that he wrote Object Lessons: Lessons Learned in Object-Oriented Development Projects, which I read years ago. (It was published in 1993.)
Pulling it out (and blowing the dust off…), the index took me to this section on testing (page 193). He says,
With an object-oriented language, one must verify that:Flipping through the book, I found this gem on pg. 231. It’s for decision makers and it’s presented in a question and answer format.
How should I choose between static and dynamic object-oriented programming languages?
It is really quite easy. Choose a dynamic object-oriented language unless you are absolutely confident that you can write the detailed functional specification for the system you are designing and that this specification will not change for three years.
We invented software because it took so long to rewire computers. Dynamic object-oriented languages make it easy to rewire computers. Static object-oriented languages use lots of solder. Resoldering is expensive and error prone.
Most applications and systems are in a high degree of flux. Choose a tool that accomodates rather than hinders this change.
To be fair, our sophisticated IDEs and their refactoring tools help this problem. Still, I wish I had paid attention to this advice at that time. It was about the time I started a UI project where I chose C++ over a few dynamic-language options. The project might have succeeded without the encumbrance…
Great quotes!
I’m not a Ruby expert but no matter what Robert Dober said, you have a “prove of concept” with deep copying of your code graph (which is done quite frequently in software) that the design violates LSP. I think it would be much easier to implement dup properly on immutable objects than having people write work arounds and spending time explaining them why it has to be this way ;-).
The thing in dynamically typed languages is that we can have a notion of type which is independent of class. I can’t recall the example, but I remember hearing that most Smalltalk implementations have some things that look like glaring LSP violations if you are looking at classes rather than some general notion of type!
Most applications and systems are in a high degree of flux. Choose a tool that accomodates rather than hinders this change…
I wish I had paid attention to this advice at that time….
I prefer the old computer nerd montra about the Liskov Substitution Principle: “If it looks like a duck, and quacks like a duck, but needs batteries, you probably have the wrong abstraction”
rom what I’ve read, Tom Love, back in the 80s, came up with an interesting notion for dynamically typed systems that seems to do what LSP does for us.. he said that in a system, every method name should mean the same thing to every caller—if you have a ‘draw’ method you have to decide whether it draws a gun out of a holster or draws a representation on some medium. ‘Draw’ should mean the same thing to everybody.
I think the key thing is that in statically typed languages, the hierarchy bears the burden of communicating substitutability information. In dynamically typed languages you can get substitution easily and that pushes people toward looking beyond the hierarchy.
I don’t know.cheap VPS
of everything, even Object, defines a method called dup, for duplicating objec
I was very pleased to find this site. I wanted to thank you for this great read!! I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.
odyssey through a breitling
cool article!Thanks for ur nice sharing!
Thank you for this nice post
my blog: alpha male | how to run faster
Mold making is the core business of Intertech (Taiwan). With world level technology, Intertech enjoys a very good reputation for making Injection Mold and Plastic Moldsfor their worldwide customers.
little bit of it and I have you bookmarked to check out new stuff you post.
So, if you thought you actually duplicated something and started messing with its methods, you would be surprised to find the original was “also” modified.
The post has shared lot of interesting information. Its great viewing. Foreclosure Process
With the right tool, you can easily burn mp4 to dvd and itunes to dvd. Also, you can use drm removal tool to remove drm protection from itunes, zune, amazon legally. wmv to dvd, mov to dvd, convert mp4 to dvd, itunes to dvd
very interesting information in this article.
i’ll bookmark this article on my webpage.
Buy $10 Replica Designer Sunglasses with 3-day FREE SHIPPING. At fashion-world4u you find Imitation ,Inspired ,MEN designer Sunglasses and Women Replica Sunglass at cheap discount price
Our backup software can help you take a snapshot for your contacts and SMS. Your important personal information will be never lost.
TopCombine Follow ipad bag the detail tips below, you can increase the laptop battery life of a year or more. Game Controllers first thing you should care about the USB Gadgets END!777777777777777777777777777777
Finally, got what I was looking for!! Thanks.
Nice and informative post.
This is a good post. This post give truly quality information.I’m definitely going to look into it. Really very useful tips are provided here.thank you so much.Keep up the good works.
Even if you don’t plan on buying your jewelry wholesale, wholesale costume jewelry stores are a great source of information on what’s currently hot in the world of jewelry. This is because these stores will typically only stock the very latest fashion jewelry designs in a wide selection to choose from. By taking a look at their collection, you will be able to know what to buy when you do find the right online retailer.
I hardly ever write comments on blogs, but your article urged me to praise your blog. Thanks for the read, I will surely favorite your site and check in occasionally. Cheers.
I think this is one of the most important information for me. And i’m glad reading your article. But wanna remark on few general things, The website style is great, the articles is really excellent. Good job, cheers
Effectively paragraph !! Thanks dean
Tüm dunyadaki okey oyunculari ile ayni platform içerisinde sohbet ederek canli okey oyunu oyna ve ve internette online oyun oynamanin zevkini çikar.
Great for Ruby learner. I try the code myself and get a useful output. thanks for sharing..
KXPOS system is all-in-one touch point of sale system,it used in restaurant pos system ,cafes,bars,pubs,clubs,supermarkets,vegetable and fruit restaurant pos pos system sydeny pos system
pos sysem hardware
point of sale hardware
pos system manufacturer
all in one touch
touch pos
touch screen point of sale
epos point of sale
yes indeed agreed
Most applications and systems are in a high degree of flux. Choose a tool that accomodates rather than hinders this change…
i’m glad reading your article. But wanna remark on few general things, The website style is great, the articles is really excellent. Good job, cheers.
Nice explanation on your blog. I sure your writing is very useful on this blog…
this is a very nice post..its very informative.. i gain a lot.. thank you for sharing this post.
i learned a lot.. its very nice very informative.. thanks for sharing this.
wow, thanks for sharing this full information post.. i really love it.
j’adore votre site, grand merci pour ces idéesC’est mon tout 1er commentaire ici et je reviendrai avec plaisir sur ce blog !
j’adore votre site, grand merci pour ces idéesC’est mon tout 1er commentaire ici et je reviendrai avec plaisir sur ce blog !
j’adore votre site, grand merci pour ces idéesC’est mon tout 1er commentaire ici et je reviendrai avec plaisir sur ce blog !
Online UK costume and fashion jewellery shop with, 456sr
Some beats by dr dre solo purple training routines that will improve Your Voice instantly when you exercise Them!These training routines are extremely effective at erasing bad habits, and replacing them using a “successful”, fabulous sounding voice. The headphone’s exterior is produced from an ultra glossy complete that’s particular to garner some attention in beats by dr dre pro black.
This is one of the most awesome design that I have seen. You are amazing buddy.Thanks, thats a nice suggestion! Will take care of it soon…
Online UK costume and fashion jewellery shop with, 456sr
very cool blog post ! i’ve been reading this blog for some time and it have cool content!
ho chi minh city is a great place for your vacations, is a wonderful city and there are the amazing hotels where you can enjoy to take a brake of your routine.
You can enjoy more your family time with a fire pit in your patio, enjoy your cold nights, too.
I am learning Ruby. I’ve got a clear idea about Fixnum object 5 from your blog. It’s really helpful.
Good Information Very nice post.
Experts often possess more data than judgment.
school to see her, afraid of boring so far way to buy the basketball magazine, all the way to see the ecstatichigh quality headphones new design headphones
Great article , very informative. For a guide to gemstones check out our site
Thank you for sharing, I’ll definitely dig deeper into it
Lots of knowledge I got from your blog thanks.
North Face Apex Bionic Kvinder Jakker
plus thighs and leg,the north face
plus improved during losing fat laden calories might move barefoot in the inclusion. In that case keep account.December 2012 will be to can comecanada goose jakke, lots of believers live 2012 is just about the most important issue with discourse. mbt internet profit internationally renowned students will be guessing devastating incidents which is nearly anything. Let’ vertisements evaluate ways to live 2012canada goose , principally around the best way far better create you actually for any predictable.
When I at first left a comment I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three notification emails with the same comment. Is there any way you can take away people from that service? Thanks a lot!
from many days i badly required these info . thanks for it ….. from here i got what i want
Expense—where employee business-related expenses are entered
Stivali Ugg Paisley , Dal, professionisti nativo di solito non sono pronte a prendere il nuove opportunità in Libia di conseguenza stanno migrando in massa verso altri paesi, la probabilità di una carriera per i cittadini internazionali è sicuramente ancora più significant.Such grande afflusso di stranieri è dotato di funzionari richiesto di produrre una legge a seconda del trenta per cento di ogni lavoratori impiegati dalle organizzazioni importati devono rimanere nationals.Nevertheless libico, commercianti e altre ditte non si dovrebbe mai sono più spesso felici usando la decisione come si suol dire, è quasi impossibile trovare quella percentuale di workforce.Ultimately libico, il vostro obiettivo conti
good post, i think so.Thank you!
Som topmødet canada goose jakke vært, har hundreder canada goose af millioner værd at Berlusconi forberedt canada goose outlet en gave til ledere: værdien af GBP 500 belstaff outlet limited edition fashion frakke.Denne mørke belstaff blå frakke siges at være “Præsidentens frakke”, udskrives canada goose jakke over Italien flag, udført Canada Goose Banff Parka af fashion brands beidafu og hr. Berlusconis samarbejde, alt ovenstående er gamle Bay autograph Canada Goose Expedition Parka drenge.Hvad angår størrelse, og gav en af lederne af alle lande er fremstillet af deres fotos og Canada Goose Expedition Parka Kvinders videoer af højden af organ oplysninger skræddersyet til.Beidafu mærke bliver Canada Goose Expedition Parka M?nd darling af fashion verden i de seneste år, mange store stjerner har passeret af mærke Canada Goose Kvinder Vest tøj, såsom USA stjernerne Brad Pitt og George Clooney, og Storbritannien har ikke iført fodbold stjerne Canada Goose Montebello Parka David Beckham.
good post, i think so.Thank you!
I confess, I have not visited this website in a long time because of my blog , nonetheless it was another delight to see such a significant subject on long distance running and I thank you for making people more attentive on possible issues.
Wow, this was a really quality post. In theory I’d like to write like this too – taking time and real effort to make a good article
Wow, this was a really quality post. In theory I’d like to write like this too – taking time and real effort to make a good article
Ma assicuratevi di carburante la vostra moto sport touring sulla strada, le fermate benzina deve essere pianificato con cura Moncler Piumini su questa strada . Per fortuna che l’inverno è stato un mite. Vegetali ChilliesThis caldo vi aiuterà a rendere la tua vita sessuale. Questo tipo di abbigliamento è disponibile per persone di diverse fasce d’età e sono disponibili in varie taglie, colori e materiali. Ma se lo fai poi scegliere 2011 Moncler Vendita in vendita una porzione più piccola, condividere con un amico o portare a casa con voi per più tardi. 18. Ecco alcuni consigli per aiutarvi a Moncler Giubbotto quella giacca moto della durata di anni. Sono inoltre dotate di polsini regolabili con soffietto e per stanza in più, hanno anche funzione di gomiti articolati.
thanks for the great stuff you have written!
An interesting discussion is worth comment.glad i came across your post, very informative indeed.
I just like to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon.
I was really impressed. This is really interesting topic. Thank you very much!
I am absolutely amazed at how terrific the stuff is on this site. I have saved this webpage and I truly intend on visiting the site in the upcoming days. Keep up the excellent work!
well. you guys really give us the sample of C++ programing skill. So. why not try this method and do a better code. next time. have another try.
Thanks for the information, I’ll visit the site again to get update information action figures
Liskov Substitution Principle and the Ruby Core Libraries 76 hoo,good article!!I like the post!13
Intertech Machinery Inc. provides the most precise Plastic Injection Mold and Rubber Molds from Taiwan. With applying excellent unscrewing device in molds,
Intertech is also very professional for making flip top Cap Molds in the world. Mold making is the core business of Intertech (Taiwan). With world level technology, Intertech enjoys a very good reputation for making Injection Mold and Plastic Molds for their worldwide customers.