Composition over Inheritance

Sdílet
Vložit
  • čas přidán 5. 09. 2024

Komentáře • 858

  • @thiagotimm3668
    @thiagotimm3668 Před 5 lety +276

    "The problem with inheritance is that encourages you to go predict the future..." Just genius Matt!

    • @jones848
      @jones848 Před 10 měsíci +1

      Yeah hearing that has been like an epiphany for me. Such a great way of looking at it

  • @AlexandriaRohn
    @AlexandriaRohn Před 8 lety +630

    07:03 "Inheritance encourages you to build this taxonomy of objects very early on in the project. And you are most likely going to make big design mistakes while doing that. Because humans cannot predict the future."
    "I think it's just better to use composition from the start. It's more flexible, it's more powerful, and it's really easy to do."

    • @hugodsa89
      @hugodsa89 Před 4 lety +15

      This is my number one problem in every single project I do. This is coming from someone who always developed in a class oop style, and now changing is so much more difficult because I am so used to what I used to do. However, I agree 100% that it is better in most scenarios, the only scenario that I would use a inheritance over composition is when I am writing a base class and I want to enforce implementation of an abstract behaviour that all objects in future must have.

    • @schirmcharmemelone
      @schirmcharmemelone Před 3 lety +3

      @@hugodsa89 So for example you make a base composition that the real compositions have to inherit?
      like returning the name or type of the composit and some sort of copy function or how to get the 'real' 'raw' data so you can leave that in an array with all other composite data of the same type in sequential memory.
      I think something the Video has not mentioned is the fragmentation of OOP data. If you want to update all poop states of all Animals then it makes no sense to jump through multiple pointers to get to the data. This would just give you cash misses and make your program slow. If you keep all position data in one sequential memory your cpu will chew right through it. Loading sequential memory can be 100x faster. Nothing beats an array.

    • @plutopulp
      @plutopulp Před 2 lety +2

      @@hugodsa89 I completely agree. The only time I use inheritance-type pattern is writing interfaces/abstract base classes, but even there it's not inheritance but enforcing implementation as you say.

    • @miltonr87
      @miltonr87 Před 2 lety

      Amazing quote! 😄

  • @Avatan5
    @Avatan5 Před 2 lety +2

    Here from The Odin Project. Great video, very helpful, and explained in a fun way too! Thank you!

  • @AlessandroStamatto
    @AlessandroStamatto Před 7 lety +121

    Composition gets better with Object Spread (sugar for Object.assign):
    return {...barker(state), ...driver(state), ...killer(state)}

    • @trappedcat3615
      @trappedcat3615 Před 6 lety

      is this standardized yet

    • @hiimshort
      @hiimshort Před 6 lety

      Red Bear it is standard, but not supported everywhere yet :(

    • @amypellegrini1732
      @amypellegrini1732 Před 6 lety +1

      You can use transpilers anyway

    • @michaelwalker1013
      @michaelwalker1013 Před 4 lety

      Was just about to comment the same thing ! That’s great! Good tip!

    • @can_pacis
      @can_pacis Před 4 lety +11

      Spread operators are not just sugar for Object.assign. Object.assign mutates the given object, thus may trigger object setters while spread operator creates a brand new iterable making it more useful with immutable techniques.

  • @ahmarsiddiqui
    @ahmarsiddiqui Před 8 lety +106

    07:03 turning point of my perception of programming in general
    I always found it hard to implement inheritance in real world applications but still used it thinking that's how I was taught oop and that's how I'm suppose to write programs
    thanks a lot for such a great video

  • @ThomasBurleson
    @ThomasBurleson Před 8 lety +99

    Inheritance is appropriate for single-level abstract classes where you define expectations of abstract methods that MUST be defined in a subclass. You effectively have written a API-contract. In almost all other cases, I favor composition. I love your videos and the style of teaching [often] techno-jargon.

    • @funfunfunction
      @funfunfunction  Před 8 lety +17

      +Thomas Burleson thanks, Thomas! And yeah, that seems like a sensible approach.

    • @ThomasBurleson
      @ThomasBurleson Před 8 lety +7

      Keep up the great work! Your videos are wonderful resources and so appreciated!

    • @davidtorroija5141
      @davidtorroija5141 Před 8 lety +2

      Me too very good teacher :D

    • @FalconFetus8
      @FalconFetus8 Před 6 lety +21

      Why not use an interface instead?

  • @SlhT-xe1cc
    @SlhT-xe1cc Před rokem +6

    I really love how extremely simple your example are presented! it really makes me roll my eyes when "beginner" guides use long-winded examples where you have to think about a thousand things at the same time and get confused and lost in concepts unrelated to what you're actually trying to learn.

  • @2thinkcritically
    @2thinkcritically Před 9 lety +25

    For those browsers that don't support Object.assign yet:
    if( !Object.assign ) {
    Object.assign = function( obj, items ) {
    var src = Object( items), target = Object( obj )
    Object.getOwnPropertyNames( src ).forEach( function( k ) {
    target[ k ] = src[ k ]
    })
    return target;
    }
    }

  • @ihateyourusernames
    @ihateyourusernames Před 9 lety +11

    By Jove! This is the most eloquent explanation as to why composition is a less complicated route than inheritance. Thanks for sharing!

  • @BenRangel
    @BenRangel Před 8 lety +279

    I blame the overuse of inheritance on college focusing too much on OOP and training us to overuse that pattern, and cram inheritance into our projects.
    A perfect inheritance hierarchy is a wonderful thing that gives you a sense of structure and a mental model. But it's not feasible in today's agile world cause it's unmaintanable. Most agile projects would benefit from using composition.

    • @cosname
      @cosname Před 7 lety +6

      Exactly! There are very rare situation where we would like to use inheritance, this idea should nailed in very narrow scenario that can be thinked as undividable unit, though should be inherited. For example of how the barker is barking actually.

    • @velocityra
      @velocityra Před 7 lety +16

      What is presented in the video *is* actually *(multiple)* inheritance.
      See the discussion here: www.reddit.com/r/programming/comments/5dxq6i/composition_over_inheritance/da8bplv

    • @PHILOSOPHYALPHAMALE
      @PHILOSOPHYALPHAMALE Před 5 lety +1

      I think so too. Java was the de facto learning language for computer science in the early 00s and OOP was everything.

    • @Ahmetfusta
      @Ahmetfusta Před 5 lety +2

      @@velocityra that was an interesting read

    • @ShaferHart
      @ShaferHart Před 5 lety +4

      @@PHILOSOPHYALPHAMALE Still is in many places and the dynamic is the same if they teach C# instead. It kind of feels very anachronistic that they still have such a heavy emphasis on OOP as if it's the end all be all of programming.

  • @daliborkozar870
    @daliborkozar870 Před 2 lety +1

    I fist watched this video 2 years ago and now coming back to prepare for an interview

  • @LethiuxX
    @LethiuxX Před měsícem

    The amount of time saved by my brain trying to figure out how to adapt classes for abstraction.
    I've just switched back to more of a functional paradigm from OOP, and it's quite refreshing.
    Composition for the win.

  • @youAmera
    @youAmera Před 7 lety +15

    Program to an interface and not an implementation - this is a good practice

  • @Rashomon69
    @Rashomon69 Před 7 lety +1

    MPJME - I've been a developer for almost 20 years. I've developed in multiple languages - COBOL, ActionScript, Objective C, Java, JavaScript, PHP, etc. I feel like I've always been "behind the curve", because I've had to learn so many languages (frequently starting over). I just discovered your channel last week, and I've been binge watching, because I have learned a LOT from them. You are filling in the pieces that I've been missing from being a "self-taught" developer. I feel like I'm now becoming the top-notch developer that I've always wanted to be. THANK YOU!!!

  • @bobbyadamson2333
    @bobbyadamson2333 Před 8 lety +1

    I have spent about a week reading things that dance around what you have explained so clearly here. Thank you for all you do

  • @robroem
    @robroem Před 7 lety

    I just have to say: You give the best example of WHY composition should be favored that I've ever seen. Anytime someone asks me, or this topic comes up; I immediately link them to your video. You explain so much better than I ever could. Thanks for that!

  • @FairyRat
    @FairyRat Před 2 lety +2

    This is so cool! I'm totally on board with composition. Also HUGE thanks for your work! Awesome stuff! The Odin Project represent!

  • @shubhamchandra9258
    @shubhamchandra9258 Před 3 lety

    Lucky to have found this video. Lesson learned: We can always opt for composition. ex- Car is a vehicle. But Car is also has wheels, engine, seats.

  • @tarekghosn3648
    @tarekghosn3648 Před 2 lety

    hell the first few lines were enough to put it in place. i found you after15 plus videos and yours was the only one who truly explained the difference in how to use them directly while thinking
    sanks

  • @anthonychung1425
    @anthonychung1425 Před 9 lety +105

    I'd LOVE it if you gave sample "tasks" for us to do to test ourselves. it sounds suspiciously like homework but it's the only way I could ever confirm I understood anything. haha

    • @funfunfunction
      @funfunfunction  Před 9 lety +31

      Oh shit, that is a FANTASTIC idea! I'll try to remember to do it next video.

    • @ChrisGeirman
      @ChrisGeirman Před 9 lety +1

      +Anthony Chung I agree... this requires practical application before I'd know I truly understand it.

    • @anthonychung1425
      @anthonychung1425 Před 9 lety +2

      yeah it doesn't have to be anything super complex or detailed. maybe just like a brainteaser or something to think about and try till the next week. :) thanks for responding!

    • @funfunfunction
      @funfunfunction  Před 9 lety +43

      +Anthony Chung It's a bizarrely good idea, I think. Especially fronting it as a "brainteaser". It would also be a interesting success metric for the video - i.e. how many was excited by the video enough to try their hand at the brainteaser, and how many understood the video well enough to solve it. I'm not commiting to doing this yet because I like to let idea mull over for a few weeks before doing them, but I really like this concept intuitively.

    • @hyperrealhank
      @hyperrealhank Před 9 lety +5

      +mpjme personally, i dont care for it. your videos are enlightening enough where i wouldnt ever feel the need for an exercise. however, i do feel like a github gist for each video would be appropriate

  • @benjonyc
    @benjonyc Před 8 lety

    I am a front end developer working in NYC. I really enjoy your explanations and have been watching your videos and coding up all the examples. I really enjoy both your explanations and when you have live coding examples. If you had a paid course I would surely purchase it. Thanks for creating this channel!

  • @darrenandveronica
    @darrenandveronica Před 8 lety +1

    I had a dream about trying to flesh out a new program with inheritance. I woke up sweating. That's totally true. Man this video was great. I watched quite a few of your vids now, you crack me up.

  • @klausdupont6335
    @klausdupont6335 Před rokem +1

    Bro makes the design patterns fun! The use cases are well-chosen and the explanation very straightforward. Nice video!

  • @jamieshelley6079
    @jamieshelley6079 Před 3 lety +1

    It's interesting, I often use both, when I know the inhereted functions will never change. Or they themselves are generics/Utility.
    Best of both words!

  • @ndbass09
    @ndbass09 Před rokem

    3.5 minutes in and I have to stop the video to like and comment...you made such a clear, sensible, and persuasive case. Thank you!

  • @praguepanda
    @praguepanda Před 9 lety +55

    This is a nice explanation. What you consider "composition" is however called "concatenative inheritance". Composition is achieved by passing more specialized components into a more general one. By doing so, you create an object model tree in which objects reference and use other objects rather than making a type tree (taxanomy) in which objects are tightly coupled to their parents (prototypal delegates or parent classes) as opposed to loose coupling in case of composition.

    • @SeyferX
      @SeyferX Před 6 lety +7

      because js and js devs are 'unique' - they invent own term definitions...

    • @rebornreaper194
      @rebornreaper194 Před 6 lety +4

      Oleg Abrazhaev "composition" is a general computer science term, not js specific

    • @jeffwells641
      @jeffwells641 Před 6 lety +2

      The way he described it in the video seems very similar to composition in Go, so I think the industry is settling on the term.

    • @panzerdp
      @panzerdp Před 4 lety +5

      Exactly! The video misunderstands the term composition, which is actually a delegation of implementation to a delegate object contained within a bigger object (has a).

  • @priyankamalviya3613
    @priyankamalviya3613 Před 7 lety

    One video and I am an ardent fan!!!!! How amazing is this explanation!!! I kept viewing this link over and over again both here as well as medium.com but never actually spent these 8-9 minutes for some reason and kept myself so confused on this topic!!!! For the first time I am so clear as to why most experienced programmers favor composition!

  • @traviszito6408
    @traviszito6408 Před rokem

    After reading a bunch of articles about this topic, I have to say you really show why composition is better in most if not all cases without over complicating things. The way you explain it deliberately and with simple language really helped me understand just what exactly composition is! I have definitely found myself in past projects saying, Well I already made this class, if I break it up or even remove it entirely then the whole program falls apart. Going forward I'm going to be more wary of this.

  • @JamesSpeirs
    @JamesSpeirs Před 6 lety

    This was so good. Clear, concise, complete, and humorous.

  • @Mr_Wiley
    @Mr_Wiley Před 4 lety +1

    You know that scene in The Office when Michael says, ok now explain it to me like I'm a 5 year old.
    Well, I feel like you just did that and it worked perfectly. I'm not learning Java but the two concepts flowed into my brain immediately and easily from this tutorial. Simple and effective, and entertaining delivery. Liked!

  • @drrecommended4850
    @drrecommended4850 Před rokem

    great explanation thank you! will definitely be running with composition over inheritance! long live the prototype!

  • @TomLikesGuitar
    @TomLikesGuitar Před 9 lety

    I'm working on transitioning many years of C++ experience into Javascript for a new job and I just wanted to say that your videos have been a great tool to help me figure out the common standards and concepts (as well as helping me prioritize what, exactly, is worth learning in this crazy-ass, over-complicated language lol). There aren't a ton of educational videos that are entertaining and well-produced, but yours manage to be both.

  • @AndrehHimself
    @AndrehHimself Před 5 lety

    I've just stumbled upon this video searching composition vs. inheritance for C# to take a second point of view as it was still unclear after watching a lesson from a course on Udemy. Your funny and practical approach was so clear and enlightening that instantly earned both my like and subscription.
    Thanks for taking your time to share it with lost travelers (:

  • @SylvainPOLLETVILLARD
    @SylvainPOLLETVILLARD Před 9 lety +4

    Wow, that is a great video. I am a huge fan of prototypal inheritance but in less than 9 minutes you just convinced me that composition outperforms the whole concept of inheritance. But then I took some time to think about it, and I found some good parts to inheritance:
    1) built-in objects in JavaScript have a huge list of properties and methods, that are spread over a prototype hierarchy like HTMLDocument > Node > Object. This hierarchy can trap you, but also help to separate layers of functionalities. So you can easily iterate on an object's properties without having to deal with all the methods inherited from Object.prototype like toString, constructor etc...
    2) with composition, everything is _flat_, which can be a good thing at first look but can lead to overly complex objects (document.body has a total of 252 properties for example)
    3) it is easy to extend a method behaviour with inheritance: you just override the function and call super() or equivalent. composing makes things quite harder : if I need to change the bark method of my RobotDog to bark(){ barker.bark("with a robot voice") }, I cannot compose it with barker. I would have to manually assign a bark method which instantiates a barker, call the original bark method in the context of the the RobotDog object, then add the extended behaviour, and things just became much more complicated.
    What are you thoughts on this ? Anyway, great video, you rocks !

    • @funfunfunction
      @funfunfunction  Před 9 lety

      All three can be done with composition just fine.

    • @funfunfunction
      @funfunfunction  Před 9 lety

      +mpjme Or rather, not iterating over all properties without hitting the parent properties, but the only reason that you need to do that in the first place is because objects contain a bunch of crap that you're not interested in.

    • @funfunfunction
      @funfunfunction  Před 9 lety +1

      2. Composed objects don't necessarily have to be flat (even though they are in my simple example) you can hide inner objects inside composed objects and only expose things that you need on the outer API surface area. Document body is that big BECAUSE it uses inheritance - that is the problem with inheritance, you get an enormous amount of functionality that you don't need.
      3. Again, just hide the inner implementation inside your composed object.

    • @SylvainPOLLETVILLARD
      @SylvainPOLLETVILLARD Před 9 lety

      +mpjme But if you hide inner objects in composed objects closures, there are no longer exposed to user ? I think the assumption "objects contain a bunch of crap" is a bit simplistic

    • @funfunfunction
      @funfunfunction  Před 9 lety

      You hide the things you want hidden. If you need something to not be hidden you just expose it. You could also expose the inner object as a property. That way, you'd get even more granularity than an inheritance model.

  • @ChristopherOkhravi
    @ChristopherOkhravi Před 6 lety

    Super good point about predicting the taxonomy being at the core of the problem. Well put. Thank you :)

  • @wypimentel
    @wypimentel Před 7 lety

    I just discovered you today, you makes things easier. And you code is so elegant, you make art with your code.

  • @juliankrispel-samsel218

    You are a genius good sir.
    This is gold!
    Funniest, simplest, most bestest articulated video thing on software design I have seen to date.
    Thanks! Keep em coming!

  • @whiskey4609
    @whiskey4609 Před 7 lety

    programmers always leave the best comments, I actually read through the comments below and was not disappointed by trolling. I ACTUALLY learned something from other peoples experiences ahahah

  • @LeonardoFrangelli
    @LeonardoFrangelli Před 8 lety

    Your videos are awesome for many reasons, but to me, the best thing is that you aways come up with the "But.....". Thanks man, and continue with this great work.

  • @edieshockpaw
    @edieshockpaw Před 4 lety +12

    Bob Ziroll's React video brought me here!

  • @moszis
    @moszis Před 6 lety

    Good god man.. you just broke my 20 years of Java experience. I'm not even kidding. Big thumbs up for this video

  • @josesousa2695
    @josesousa2695 Před 3 lety

    Very well explained, and it's true : use composition

  • @jakubrpawlowski
    @jakubrpawlowski Před 7 lety

    Great video! I've just read 100 pages on inheritance in "Secret of the JavaScript Ninja" by John Resig and I had so many doubts about going this route and now I have an alternative to explore. Thank you so much!

  • @peripona
    @peripona Před 8 lety +13

    At First.. I felt reluctant to watch the video with such Handsome Poster Image ( : Scarcastic :D )
    But then...
    I am spellbound by the way you have conveyed such a concept with such innovative, indulging and entertaining way..
    Kudos. Yo!! your video rocks. I ill subscribe and follow your Videos :)
    With love from India !

  • @danmartin1726
    @danmartin1726 Před 8 lety +1

    Love this "Real World" explanation training style. Great job!

  • @dylanking000archive
    @dylanking000archive Před 2 lety

    came from the odin project. can't remember if it was linked directly there or if this was linked in an article they had me read. I love your energy and you explained this in a way where somebody who's struggling came away knowing more than I did. thanks so much.

  • @Andrey-il8rh
    @Andrey-il8rh Před 3 lety

    For me, a great pivotal point in understanding composition over inheritance was (surprise surprise) a move from BEM to Tailwind. It just proved itself so much more powerful when you can compose your interface from utility classes rather than writing inherited Block Element Modifier rules

  • @stevehyuga9216
    @stevehyuga9216 Před 6 lety

    Thanks for your videos, they are amazing.
    After watching the video I didn´t know how to change the state, if it needs to be changed. I put my fingers in movement and I found two approaches:
    1st, use a setter:
    const barker = (state) =>({
    bark: () => console.log(state.sound)
    })
    const setter = (state) =>({
    set: (key,prop) => {
    state[key] = prop
    }
    })
    const dog = (name) => {
    let state = {
    name,
    sound: "woof"
    }
    return Object.assign(
    {},
    barker(state),
    setter(state)
    )
    }
    let rufus = dog("rufus")
    rufus.set("sound", "I'm rufus")
    rufus.bark() // I'm rufus
    2nd, use state to create the object:
    const dog = (name) => {
    let state = {
    name,
    sound: "woof"
    }
    return Object.assign(
    state,
    barker(state)
    )
    }
    let rufus = dog("rufus")
    rufus.sound = "I'm rufus"
    rufus.bark() //I'm rufus
    Which approach you think is better?
    Thanks in advance.

  • @ariemilner8845
    @ariemilner8845 Před 8 lety

    Absolutely love your show, I think your show is so beneficial (and fun and interesting and awesome etc...) not just because of your skills as a programmer, but also your ability to *keep things simple* in your explanations! Often people explaining things like to over complicate things to "sound smarter".... not fun at all.
    Please keep it up!!!!

  • @ahh-sure
    @ahh-sure Před 11 měsíci

    I like the focus on what objects *do* versus what they *are.* This is a good example of a shift from one pattern to another. However, it relies on an unknown object (called "state") for the factory function pattern, and might make it more difficult to understand how the composition example maps onto the inheritance-based design. So, firstly, you'll still need an interface or a type for the "state" object passed into the factory functions -- in this case, it must have "position" and "speed" attributes for the drive method of "driver" to work. Secondly, if "barker" relied on any additional attributes, you would need to ensure the state object implemented those. This leaves you with the need for additional interfaces (which themseleves may or may not use inheritance for other reasons).

  • @keplar7243
    @keplar7243 Před 4 lety

    Thank you so much for these videos they're by far the most concise yet clear and straight to the point.

  • @T-She-Go
    @T-She-Go Před 3 lety +3

    "Its like you ask for a banana and you get the banana but a gorilla is holding it" 😂😂 I love this. Thank you so much🙌🏾

    • @souravkb
      @souravkb Před 3 lety +1

      And the entire jungle with it!

  • @yitzhakkornbluth2554
    @yitzhakkornbluth2554 Před 7 lety

    The way I learned the is/has distinction isn't as composition vs. inheritance (where it really makes no sense, as you said), but rather as how you decide whether something should be a subclass (which can be done via composition or inheritance) or a member object.
    I see inheritance as an attempt to port over a concept from languages where it makes sense (more strongly typed languages make composition much more difficult if not impossible) to a language that doesn't really need it.

  • @Vilmir
    @Vilmir Před 8 lety

    A young Christopher Waltz explaining engineering concepts quite well. This kid has a future :)

  • @kunalpareek83
    @kunalpareek83 Před 7 lety

    Man this is such a fantastic vid. Thanks for the wisdom. Inheritance seems like such a natural way to think about things. (I was introduced to classes via Django) but I have faced the exact problem you defined above. Must rethink object construction using composition.

  • @lamnot.
    @lamnot. Před 6 lety

    This is so funny, I am using composition strategy it in solidity and it works perfectly. The mechanism there are modifiers, they also grant permissions as well.

  • @nosajghoul
    @nosajghoul Před 6 lety

    Dude I just answered a question about composition on quora and referenced this video and the picture it chose to use of you is freaking hilarious.

  • @elmarvo7505
    @elmarvo7505 Před 2 lety +1

    Such a brilliant example! Thanks a lot

  • @TheTwalnb
    @TheTwalnb Před 7 lety

    I agree with Antony Chung. Some sample tasks would be greatly appreciated. I am new to coding and find it difficult to find tasks that might further my understanding of the more complex concepts. Thanks!

  • @StephanHoyer
    @StephanHoyer Před 9 lety +1

    You speak to me from the soul, as always. Great video.
    Composition outperforms prototypal Inheritance not only in simpler structure but also in better readability due to the fact, that you don't have to use that f.....g "this" anymore.
    Sadly I can't come to this years JS-Conf because some serious childbirth is going one here :). I'd love to have a chat with you there.
    Have Fun in Berlin!

  • @IsaacC20
    @IsaacC20 Před 6 lety

    We need one of you ... for each programming language.

  • @Gruak7
    @Gruak7 Před 4 lety

    Those examples are absolutely top notch

  • @neozoid7009
    @neozoid7009 Před 2 lety +1

    Awesome explanation also very funny , why I didn't seen this channel♥️👍

  • @HeilTec
    @HeilTec Před 7 lety

    Composition of capabilities is a very good design pattern.
    The new features makes it even more advantageous.
    // Shorthand property names (ES6)
    a=1;
    b={a}; // { a: 1 }
    As functional programming also employs composition it seems fitting to think like a composer rather than a geneticist.

  •  Před 9 lety +1

    I especially like this video! Very exciting to learn about composition :)
    Really thankful for your videos, they are informative without being boring, and tells me just enough about a topic to get me excited about diving deeper into it.
    Would be nice to hear about some more ES6 goodies that I should be using!

    • @funfunfunction
      @funfunfunction  Před 9 lety

      +My Högblom Thanks, My! Might be some ES6 stuff coming in the pipe, we'll see!

  • @raselkarim2731
    @raselkarim2731 Před 3 lety

    I couldn't wait to subscribe to your channel after watching this video. Love.

  • @klesk44
    @klesk44 Před 7 lety

    As a (French ^^) PHP developer, your JavaScript approach is so interesting and so clear !
    Thanks a lot for sharing your skills :p
    And stay curious ;)

  • @thesravan079
    @thesravan079 Před 8 lety

    A super tutorial I found about Composition and Inheritance in JavaScript. Thanks mpjme!

  • @adamzerner5208
    @adamzerner5208 Před 7 lety

    LIGHTBULB!
    You just made my day. You just leveled up my programming skills in 8 minutes. Thank you!

  • @carinlynchin
    @carinlynchin Před 7 lety

    BEAUTIFUL. thanks so much for the easier description. I have been hearing about it but, let's be honest, a lot of the resources befuddle their explanation to a bunch of terms and I personally learn better with examples. So thank you. I actually started learning OOP in college, so it is pretty hard wired into my mind until the job I'm in which they dont' want OOP... I never understood why until I started reading about this recently.

  • @cosname
    @cosname Před 7 lety

    I love how you described the problem of composition vs inheritance.
    From my experience, i see inheritance as powerful tool how the small tool-set, or a feature, that has been developed. Small enough that a structure can be reorganized, and inheritance rethink-ed again. Usually like up 2 or 3 levels, but possibly no limitation if this hole deepness is predictable from code design.
    So to be more specific. Pure composition says that there are used, and those who use. Only 2.. Master and the slave. If we think about inheritance we have a common behavior for all set of parent->child->...->child and those can be used as object of 1st level only.
    From this given example are only for showing the benefit of composition. Benefit from inheritors is all about how Barker barks, or meower "meows", where the inheritance will be a better choice. Thank you!

  • @Brandon_1738
    @Brandon_1738 Před rokem +1

    Came here from odin project. Great video

  • @AngusMcIntyre
    @AngusMcIntyre Před 7 lety

    With a statically typed language, inheritance is great for extension. I almost never use it for defining domain concepts, more for elegantly tapping into the language - a workaround :D

  • @fcap_2023
    @fcap_2023 Před 7 lety

    I started understand behavioral composition is more powerful than inheritance via concept...thank you for your easy-to-understand video! Appreciated sharing your opinion, learn something new about JS! :)

  • @IntegralDeLinha
    @IntegralDeLinha Před rokem

    Thank you! This was very useful and insightful!

  • @codefinity
    @codefinity Před 4 lety

    Even though this video is 5 years old, it's still is greatly applicable. 👍🏽

  • @addisonfrancisco9007
    @addisonfrancisco9007 Před 4 lety

    This is such a great use of analogies.

  • @jeffersonian4
    @jeffersonian4 Před 6 lety

    Fantastic. This is easily the best explanation of classical vs prototypal inheritance I've run across. Great vid! New subscriber right here

  • @IhsanMujdeci
    @IhsanMujdeci Před 7 lety

    This paired with inversion of control s a sick programming style.

  • @andreasonny83
    @andreasonny83 Před 7 lety

    straight to the point and crystal clear

  • @sc76399
    @sc76399 Před 9 lety

    Brilliant video, loved the Robot Murder Dog made me laugh. It's very thought provoking and I love the idea of composition because you only get the functionality that you need over all the functionality you might need or just because some other children use that functionality I'm going to have to learn more about it.

  • @proclaimm
    @proclaimm Před 8 lety

    first time seeing your video from a friend's referral, haha, you crack me up and it's interesting to see daily life example that you used to better illustrate the concept. thank you and I subscribed.

    • @funfunfunction
      @funfunfunction  Před 8 lety

      +Jim Kang Hey jim, that's great to hear. Welcome to the channel and say thanks from me to your friend!

  • @auchucknorris
    @auchucknorris Před 5 lety

    im going to use this as the bases for my future programming, after going down a rabbit hole of inheritance, fake classes, i keep hearing about all the problems associated with "this" and how the paths can be convoluted, even for me to understand watching the examples it becomes almost impossible to follow the path

  • @grancubodemierda
    @grancubodemierda Před 8 lety +1

    Interesting... what you are doing there is more or less what you can achieve in python by using multiple inheritance. Each of your barker/driver/killer is what I would call a mixin. I always thought of composition as instantiating objects and attaching them to your main object, not as "mixing" all of them into the same object (or namespace if you will).
    Anyway, thank you for the video, I learnt a lot.

    • @funfunfunction
      @funfunfunction  Před 8 lety

      +ikaros45 absolutely. When I say composition in this video it is basically a garble of mixins and multiple inheritance. I wouldn't even begin to know where to draw the line between all those things to be honest. The main point that I wanted to get across was "be skeptical of the industry default that is single inheritance".

    • @grancubodemierda
      @grancubodemierda Před 8 lety

      +funfunfunction hehehe I thought I could clearly tell composition from inheritance, but you got me thinking if mixins with a small and well defined functionality can be considered composition... and it does not sound like something crazy.
      However, I tend to think that your composition is rather inheritance, mainly because of the fact that when you compose "driver" into your "killer", the "driver" interface gets mixed with your "killer", which is not the case when using composition. But yeah, to be honest, as I am writing this I realize that... what if you consider that the main actor is not "killer" but the mix "killerdriver" itself? can you say that you compose one into the other? Not really... now I understand what you meant with the ambiguity of "is" or "has". Maybe it's time to coin the term comporithance :D

    • @funfunfunction
      @funfunfunction  Před 8 lety

      +ikaros45 Comporithance! Now you're thinking like Rich Hickey. ;)

  • @micaevski
    @micaevski Před 9 lety +4

    hey, love your show.
    can you please make an episode about modules and separation to different files.
    thank!

  • @doug2k1
    @doug2k1 Před 8 lety +2

    Just found about your channel. Clear and fun explanations! Keep up the good work!

  • @gianlucapaul
    @gianlucapaul Před 7 lety

    I really appreciate your videos MPJ. I'm not working as a front end dev yet but I think these vids will get me there sooner rather than later.
    I also really enjoyed starting this video at 1:52 at 50% speed and seeing how drunk you sound :-).

  • @tijilparmar1642
    @tijilparmar1642 Před 3 lety

    Love this video..clared the concept with humour...

  • @silvgravity4492
    @silvgravity4492 Před 4 lety

    awesome video! i feel like these 8 minutes made me a much better developer

  • @Nerdcoresteve1
    @Nerdcoresteve1 Před 8 lety +4

    I love this. Inheritance is a pain in the ass.

    • @napillnik
      @napillnik Před 8 lety +2

      +Nerdcoresteve1 maybe you're just thinking about it in the wrong way?

  • @adamo901
    @adamo901 Před 4 lety

    Outstanding tutorial, thanks a lot.
    I really liked the way you presented this topic.

  • @swaroopbhave651
    @swaroopbhave651 Před 5 lety

    Superb comparison. Hats off

  • @Slipaa2
    @Slipaa2 Před 8 lety

    You're right. It's a definitely a problem to interface segregation (composition), not inheritance, but you don't necessarily need functional programming to achieve this. Even Javascript soon will have the decorators to address this issue. :P

    • @1DJLNR
      @1DJLNR Před 8 lety

      But be carful, javascript is still not what many people think it is, put simply, javascript is a powerful scripting language to actually run gigantic premade super functions using C way in the background aand lets not ever forget it, i say that toto say this, books will set many wanna be programmers free, youtube is great but without that book stuff one could never explain let alone write a spa ground up without jquery..

  • @professorfontanez
    @professorfontanez Před 8 lety

    Well put. Your reasoning about why we should never use inheritance has a lot of merit. However, I think that your statement that we cannot predict the future is a little bit extreme. While true we cannot predict the future to a 100% certainty, we can make some inferences based on things we know today. For example, we can statistically predict the probability of something not changing in the future based on historical data. So, based on that, if I am trying to model a hierarchical relationship of an entity that has maintain that type of relationship over the years, I would use inheritance to model that.I do think there is still some relevance in using inheritance. But, I really enjoyed your presentation. Very well done, sir. (I did hit "like" even though I disagree on the point of never using inheritance).

  • @bobdudan
    @bobdudan Před 8 lety +1

    Even though I agree that it is easier to think of what an object "is doing" rather than what "it is", it is very easily doable with interfaces. In your example, I would have many interfaces (bark, poop, drive) and each class would implement the interfaces t needs.

    •  Před 8 lety

      +bobdudan Having classes that implement multiple interfaces actually is "composition" as described in the video. It's only when you start to share implementation details between the classes that you are in trouble. In simpler terms for Java programmers: "implements" is good and "extends" is bad.

  • @rindiainvestments9878
    @rindiainvestments9878 Před 8 lety

    Loved the Gorilla Banana analogy! If I recall correctly, Erlang's creator Joe Armstrong said something similar.

    • @cleoz9274
      @cleoz9274 Před 8 lety

      +Veritaserum And then many, including Eric Elliott, repeated it.

  • @gutovp
    @gutovp Před 2 lety

    I've been taught in college the inheritance concept as one of the core concepts for OOP. Inheritance is widely used, now and then one will encounter it. The composition concept is much more flexible and maintainable, though. I'd rather implement composition, but I think it is important to know the inheritance syntax.

  • @narongsakyooyen9572
    @narongsakyooyen9572 Před 2 lety +1

    great explaination, thanks

  • @shaneunger
    @shaneunger Před 7 lety +18

    I'm new to the concept of factory functions (well, JS in general) but I understand Object.prototype.someMethod as a way of creating methods or properties that an object can inherit. One of the major benefits as I understand it is that if you have your object inherit methods rather than instantiating objects with them it's more memory efficient. Using this concept of factories, and composition, are you getting the same benefits? If I create 10 murderRobotThingies, am I creating 10 objects each with their own method, or are they kind of inheriting the method, almost like I used the Obj.prototype pattern?

    • @PRATIK1900
      @PRATIK1900 Před 4 lety

      Same Question. notice us mpj senpai

    • @ericg3065
      @ericg3065 Před 4 lety

      3 years and still no answer

  • @cupofkoa
    @cupofkoa Před 7 lety

    The interesting thing is that composition is thought of as 'has a' but in your examples you name the abstract objects as 'barker', 'driver', 'killer', etc. which sounds more like 'is a' to the composite object. So although MurderRobotDog is a composition of objects, it 'is a' 'barker', 'driver', 'killer' - rather than 'has a' 'barker', 'driver', 'killer'. So although its composition, it sounds and almost feels like inheritance.