Liskov Substitution Principle and the Ruby Core Libraries 78

Posted by Dean Wampler Sat, 17 Feb 2007 20:20:00 GMT

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.

Specifically, as the ruby-talk discussion title says, it’s the immutable classes (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.

In fact, Ruby makes this sort of AOP easy to implement. Maybe 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

Comments

Leave a response

  1. Avatar
    Michael Feathers about 5 hours later:

    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.

  2. Avatar
    Dean Wampler 2 days later:

    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:
    • all inherited methods used by the class are correct
    • all arguments that are subclasses of the specified argument type are correct
    • all methods by the same name perform the same logical operation
    • the documentation is accurate…


    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…

  3. Avatar
    Michael Feathers 2 days later:

    Great quotes!

  4. Avatar
    Sebastian Kübeck 4 days later:

    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 ;-).

  5. Avatar
    asserd 3 months later:

    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!

  6. Avatar
    trenton 3 months later:

    Most applications and systems are in a high degree of flux. Choose a tool that accomodates rather than hinders this change…

  7. Avatar
    brandy 3 months later:

    I wish I had paid attention to this advice at that time….

  8. Avatar
    lil wayne over 3 years later:

    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”

  9. Avatar
    cheap vps over 3 years later:

    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

  10. Avatar
    bag manufacturer over 4 years later:

    of everything, even Object, defines a method called dup, for duplicating objec

  11. Avatar
    oyun over 4 years later:

    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.

  12. Avatar
    Chanel cambon over 4 years later:

    odyssey through a breitling

  13. Avatar
    Designer Bags over 4 years later:

    cool article!Thanks for ur nice sharing!

  14. Avatar
    Harrishcolin over 4 years later:

    Thank you for this nice post

    my blog: alpha male | how to run faster

  15. Avatar
    Silicone Molding over 4 years later:

    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.

  16. Avatar
    jocuri fotbal over 4 years later:

    little bit of it and I have you bookmarked to check out new stuff you post.

  17. Avatar
    Criminal Records over 4 years later:

    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.

  18. Avatar
    ssara over 4 years later:

    The post has shared lot of interesting information. Its great viewing. Foreclosure Process

  19. Avatar
    dvdsoft over 4 years later:

    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

  20. Avatar
    cable ties over 4 years later:

    very interesting information in this article.

  21. Avatar
    cable ties over 4 years later:

    i’ll bookmark this article on my webpage.

  22. Avatar
    Sunglass over 4 years later:

    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

  23. Avatar
    iPad Video Converter for Mac over 4 years later:

    Our backup software can help you take a snapshot for your contacts and SMS. Your important personal information will be never lost.

  24. Avatar
    ipad bag over 4 years later:

    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

  25. Avatar
    SEO Firm India over 4 years later:

    Finally, got what I was looking for!! Thanks.

  26. Avatar
    Answers over 4 years later:

    Nice and informative post.

  27. Avatar
    dory over 4 years later:

    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.

  28. Avatar
    cheap fashion jewelry over 4 years later:

    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.

  29. Avatar
    Freelance SEO India over 4 years later:

    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.

  30. Avatar
    programy over 4 years later:

    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

  31. Avatar
    okey oyunu oyna over 4 years later:

    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.

  32. Avatar
    Best Lip Moisturizer over 4 years later:

    Great for Ruby learner. I try the code myself and get a useful output. thanks for sharing..

  33. Avatar
    pos system over 4 years later:

    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

     

  34. Avatar
    funny pictures over 4 years later:

    yes indeed agreed

  35. Avatar
    massager over 4 years later:

    Most applications and systems are in a high degree of flux. Choose a tool that accomodates rather than hinders this change…

  36. Avatar
    Schnauzer Problems over 4 years later:

    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.

  37. Avatar
    ford leveling kit over 4 years later:

    Nice explanation on your blog. I sure your writing is very useful on this blog…

  38. Avatar
    leveling kit ford over 4 years later:

    this is a very nice post..its very informative.. i gain a lot.. thank you for sharing this post.

  39. Avatar
    leveling kit f250 over 4 years later:

    i learned a lot.. its very nice very informative.. thanks for sharing this.

  40. Avatar
    f350 leveling kit over 4 years later:

    wow, thanks for sharing this full information post.. i really love it.

  41. Avatar
    laptop ieftin over 4 years later:

    j’adore votre site, grand merci pour ces idéesC’est mon tout 1er commentaire ici et je reviendrai avec plaisir sur ce blog !

  42. Avatar
    jucarii over 4 years later:

    j’adore votre site, grand merci pour ces idéesC’est mon tout 1er commentaire ici et je reviendrai avec plaisir sur ce blog !

  43. Avatar
    poker ca la aparat over 4 years later:

    j’adore votre site, grand merci pour ces idéesC’est mon tout 1er commentaire ici et je reviendrai avec plaisir sur ce blog !

  44. Avatar
    Jewellery over 4 years later:

    Online UK costume and fashion jewellery shop with, 456sr

  45. Avatar
    beats by dr dre headphones over 4 years later:

    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.

  46. Avatar
    play arcade games over 4 years later:

    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…

  47. Avatar
    mmorpg over 4 years later:

    Online UK costume and fashion jewellery shop with, 456sr

  48. Avatar
    deadbeat millionaire over 4 years later:

    very cool blog post ! i’ve been reading this blog for some time and it have cool content!

  49. Avatar
    ho chi minh hotels over 4 years later:

    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.

  50. Avatar
    firepit over 4 years later:

    You can enjoy more your family time with a fire pit in your patio, enjoy your cold nights, too.

  51. Avatar
    Community Service Online over 4 years later:

    I am learning Ruby. I’ve got a clear idea about Fixnum object 5 from your blog. It’s really helpful.

  52. Avatar
    audio converter over 4 years later:

    Good Information Very nice post.

  53. Avatar
    swimsuit coverups over 4 years later:

    Experts often possess more data than judgment.

  54. Avatar
    beats by dre store over 5 years later:

    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

  55. Avatar
    Jewellery XY over 5 years later:

    Great article , very informative. For a guide to gemstones check out our site

  56. Avatar
    dvd ripper over 5 years later:

    Thank you for sharing, I’ll definitely dig deeper into it

  57. Avatar
    Web Designing over 5 years later:

    Lots of knowledge I got from your blog thanks.

  58. Avatar
    louboutin over 5 years later:
    At some time extensive most effective low-priced MBT Kafala Boots and shoes discounted design all these cycles boots and shoes, Jimmy Choo Pompesyou may the radical the answers.Jimmy Choo Sandales Quite a few job opportunities have to have you actually often be humiliated with you, fully to the specific shape, ankles,

    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.

  59. Avatar
    DR OZ african Mango over 5 years later:

    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!

  60. Avatar
    juicy couture tracksuits over 5 years later:

    from many days i badly required these info . thanks for it ….. from here i got what i want

  61. Avatar
    Ashley Bowling over 5 years later:

    Expense—where employee business-related expenses are entered

  62. Avatar
    Stivali Ugg Paisley over 5 years later:

    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

  63. Avatar
    flac converter over 5 years later:

    good post, i think so.Thank you!

  64. Avatar
    canada goose jakke over 5 years later:

    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.

  65. Avatar
    christian louboutin over 5 years later:

    good post, i think so.Thank you!

  66. Avatar
    storage Singapore over 5 years later:

    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.

  67. Avatar
    travel deals over 5 years later:

    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

  68. Avatar
    travel deals over 5 years later:

    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

  69. Avatar
    Moncler Piumini over 5 years later:

    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.

  70. Avatar
    tv guide over 5 years later:

    thanks for the great stuff you have written!

  71. Avatar
    air-con repair over 5 years later:

    An interesting discussion is worth comment.glad i came across your post, very informative indeed.

  72. Avatar
    exit and emergency lights over 5 years later:

    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.

  73. Avatar
    bhutan travel guide over 5 years later:

    I was really impressed. This is really interesting topic. Thank you very much!

  74. Avatar
    grad school personal statement over 5 years later:

    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!

  75. Avatar
    iPhone sms transfer over 5 years later:

    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.

  76. Avatar
    youngbrown over 5 years later:

    Thanks for the information, I’ll visit the site again to get update information action figures

  77. Avatar
    louboutin sales over 5 years later:

    Liskov Substitution Principle and the Ruby Core Libraries 76 hoo,good article!!I like the post!13

  78. Avatar
    Injection mold over 5 years later:

    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.

Comments