This is a companion discussion topic for the original entry at https://thoughtbot.com/upcase/videos/composition-over-inheritance
Great episode. 'Prefer Composition over Inheritance` is something that I hear often but usually neglect to apply it, I guess because my brain is wired with a more ‘inheritance’-like style of thinking. I’ll need to watch this a few more times to help it sink in.
A couple of questions:
- Are there any situations where traditional inheritance still makes sense? Or is it better to always go with composition to provide for more flexibility as code grows over time?
- And what about Ruby modules, should they generally treated as a code smell? How do you evaluate whether they are a good choice or not?
@andyw8 I’ve seen Sandi Metz (I recommend watching that whole video if you haven’t already) say that inheritance is good when a subclass basically overrides some methods and very little else, kind of Interface Segregation Principle related - as in don’t inherit from a super class just to get a tiny subset of behaviour that’s not core to the purpose of that class, prefer composition in that case.
By coincidence just I watched that just a few days ago. It was a very useful companion to the ideas presented in the episode.
Great discussion. I feel like there was a lot of agreement that we should almost always use composition over inheritance. Having said that I wanted to challenge that there are cases where one would use inheritance/include.
For example when creating an API wrapper it seems to be common practice to include all functionality required in a client via includes. I thought maybe there is a way to leverage composition, but I haven’t been able to come up or find any examples. I also checked what APIs thoughtbot has written and found that they have worked on the Yam Gem which has been contributed to by thoughtbot and I wanted to find out why is it ok to use includes in the client library? This seems to contradict what is said in the discussion.
Any help would be appreciated.
Yes, sorry I thought I included that link. That is what I am referring to.
- Do you two think that Rails’s use of inheritance is a poor design choice?
- Or is there something about the type of software that Rails is – a web framework – which makes it a strong and practical candidate for inheritance?
- If Rails’s use of inheritance is a good design choice, then do we have a use case where we choose Inheritance Over Composition?
Also, the above questions are not just for Ben and Joe. Feel free to chime in anyone and everyone.