Only registered users can comment.

  1. 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.

  2. Ah, that was always bugging me about some games, where they would use an AI Actor Factory that you specify a bunch of classes to make the character to spawn. What weapons, what AI, what character model, where to spawn…. I think Composition should be used when you need to use some but not all of the functions. Helper Classes that contain a bunch of helper methods is how I've done some tricky code, where the class is just meant to store functions to assist the data being processed. That however is because I am interfacing with already existing code, I don't get to modify the entire function set.

    But as for "pure" composition I think having one class that you can define what will be used and then making that class the only class to be referenced in a bigger class. Like a menu to order from, you have options, you order what you want to have and it is served to you. I recommend using it where you expect functionality to vary when performing the same action such as ordering food.

    Ex. Attack -> Based on what the instance has equiped or not, it grabs the data it needs from a weapon (which stores what animation to perform or what combo is allowed, or what move it is currently on in a combo, or display on screen a combo hit to perform based on the weapon) or even entirely allows the weapon to decide the next course of action without going back to the thing that wanted to Attack. You could call Attack with some parameters as well which could influence allowing a basic combo or advanced combo from an AI enemy if you wanted the AI to determine how well it can use a weapon, but the combos would be stored in weapon. That way you are keeping AI Attacker related functions in one place and weapon related functions in one place.

  3. What if you used two object literals. The first one is filled with only methods and the second one is filled with just properties. Then as you declare new objects you pull what you need for each object out of the two literals? Would that be considered compositional?

  4. Single level inheritance is fine like in case of React where we make a class inherit from React.Component, if you want to do anything more then go with composition without a second thought

  5. When connecting to an API we have common get, getall, create, update, delete… would inheritance not be better for that?

  6. This is super awesome video! I have been being heard from many folks that class is not so much good as we expect. But I didn't really know why exactly before I saw this video. Now I understand clearly how factory function and composition can be beneficial in my daily coding! Thanks!!

  7. This video does a terrible disservice to programmers. It's misleading and somewhat ignorant. The fact is, composition and inheritance are merely tools, and tools are not intrinsically good nor bad. In the right situations, these tools can be very useful.

    "Always choose the right tool for the job."

    Has the inheritance tool been misused in the past? Probably, but that's not the tool's fault. It's the fault of erroneous education and training.

    To suggest that composition should almost always be used instead of inheritance is just plain irresponsible. My colleagues and I have used Smalltalk for decades to write large, maintainable, reliable, enterprise applications very successfully. These applications have relied heavily on inheritance. When done right, the benefits are very clear: code reusability is a reality; the size of the code base shrinks significantly; and the complexity of the system is well-managed.

    At the same time, I can tell you that we use composition where it makes sense. It has always been a part of object-oriented programming and the Smalltalk ethos. I refer you to an excellent text on the subject: "Smalltalk, Objects, and Design," by Chamond Liu (© 2000 iUniverse).

  8. Wouldn't one create a lot of redundant code when creating similiar objects. Here is an example of two types of cell objects, UnderlinedCell uncorporates the TextCell object. Would you approve of that or is it again just inheritance?
    const TextCell = (text) => {
    //console.log("text: %s, type: %s", text, typeof text)
    let state = {
    text: text.split("n")

    state.minWidth = minWidth;
    state.minHeight = minHeight;
    state.draw = draw;

    return state

    const UnderlinedCell = (text) => {
    const textCell = TextCell(text);
    const minHeight = () => textCell.minHeight() + 1;
    const draw = (width, height) => textCell.draw(width, height -1)
    .concat(repeat("-", width));
    return {…textCell, minHeight, draw}

  9. 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.

  10. There is this article here, saying that in your video you do not actually show composition but hidden inheritance: Could you clarify?

  11. @1:14 "We also need a… murder robot; that can drive and kill all the cats and dogs that are pooping"

    And I knew that the video would be nice.

  12. when state object is created it takes directly the value of name and assign it directly to the object (no index added) why so? does it takes the name as a pair (same var name to object index and var value as index value) ?

  13. In the example you showed I have noticed that this type of composition has a much higher memory footprint. Multiple Murder robots would not share a prototype object. Therefore new objects would be created for each function you are defining, rather than sharing a function and just executing it in different contexts.

  14. I love the idea of mix-and-match types, it's like the best of both worlds between Classes and Interfaces. However, wouldn't it be difficult in a larger scale app to keep track of which properties are in which classes? Say I wanted to add "barker" into the Object.assign – wouldn't I have to check ALL my other factories to make sure I'm not overwriting anything?

  15. Is this a right way of composition?


    const abilities = {
    canSound: (
    const machine = function(){
    this.sound = 'I am a machine.';
    machine.prototype.mkSound = abilities.canSound;
    const animal = function(){
    this.sound = 'I am a animal.'
    animal.prototype.mkSound = abilities.canSound;

    const car = new machine();
    const bird = new animal();


  16. If I had a nickel for every MurderRobotDog implementation… Then I'd have… Uh, how do you convert it to Swedish kronor? If they handle amounts of money in the same way they do distance then I'd say it's… Within an inch of a dollar, assuming dollars are represented in base10. It's like a foot of quarters of you have regular sized feet and you lay them out on your foot without the coins overlapping unless you're using the Gregorian calendar; in which case you have to convert it into JSON before parsing it by POSTing the contents physically to the Federal reserve and waiting for either a timeout or a police car to show up. So all in all I'd recommend not going insane and posting incoherent YouTube comments.

  17. I'm starting to seriously question the dogma surrounding "mainstream" dev practices. The class hierarchies I've worked with and created myself have ended up way too brittle and therefore static, leading to hard to diagnose bugs and code duplication as the only practical mean of extension. But that's a smell we can't handle, so it's always a rewrite into a new class hierarchy. This time we introduce generics and whatever concepts we can summon from The Depths of Documentation. Many unspeakable horrors have been created this way.

    I think it comes down to how we learn new programmers to model programs. Always thinking in terms of things which turn into objects (yay, incapsulation is GREAT) instead of doing the (initially) slightly more cumbersome thing and look at programs as things that transform data and which abstractions we can use to build structures that fit exactly what we're trying to do/express. Class is a tool, not a silver bullet.

    I'm currently in a functional programming honeymoon phase where I see how simple and powerful it is to think about what data you have and then simply build things that operate on that data. Add some cool tools to glue operations together and you get programs that are very simple to understand but at the same time so, so expressive.

    Rant over.

  18. The one argument in favor of inheritance I've heard (from someone who hates inheritance mind you) is that the very first child inheritance, the "b inherits x from a" level, allowed for massive compiler optimization that you just can't get any other way. It also breaks after the very first inherited pair (so a second or third child object would not see the optimization), so it is hard to take advantage of.

    He was writing a game, and decided this one compiler optimization was worth writing a giant super-object as his game object, with all necessary elements for all of his object types inside, and dealing with all of the negative consequences of that, just to get that inheritance optimization.

  19. I went back to Solid and now I can tell that the problem here is a violation of Liskov and perhaps interface segregation. Obviously, you can fix this by moving few things around, but I think the point here is to have that approach from the outset, rather then figure it out along the way, when too much code is already written.

  20. What if you don't have coherent groups of properties and methods to break down your composition?

    Most of the time I have this composition/inheritance conundrum, it comes down to the fact that if I were to implement composition, I'd just have a separate interface for each property and method, where modelling an "is a" relationship does not require this.

    The problem is that I'm not working with the simplistic examples people give in videos and tutorials. I am never going to be writing an application to model animals and cars and bicycles. I'm working with things that are more abstract than that, with no coherent grouping mechanism. Trying to figure out what properties and methods should go together is every bit an exercise in predicting the future as modelling inheritance relationships.

  21. Great explanation, totally agree! I have a further question, why use ugly Object.assign? Instead of the pretty:
    return {

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

  23. Thanks for the video. Your examples were a lot of fun, as promised. I would like to add something on the topic of inheritance vs. composition, and when to use each. I thought of one example where inheritance is desirable over composition, and that is in cases where it is important to have implied identity. Allow me to elaborate.

    Say for example you are implementing a system that parses a list of tactical symbols for a real-time military logistics application. In this list there are hierarchy of things. There might be a unit, and among these units there are various types, like infantry, artillery. Infantry might be further subdivided into other types, like engineers, riflemen, etc. The way the army did things, these hierarchies have more common symbols; any infantry can be represented by the infantry symbol, and it is not wrong to do so. More markings are added to make each type more specific. So if you have a rifle unit, you might represent it with the rifle-infantry symbol or just the infantry symbol. It's more correct to use the specific symbol, but in some scenarios (like strategic overlays), you might just want to represent all the infantry with their most general symbol, infantry.

    So what do you do to draw a huge list of these symbols? You might create a class, call it TacticalSymbol(). The main drawing routine is a loop that simply calls Draw() on each item in the list.

    In your example, what would you Object.assign()? You would add Draw() to it. Now, say you wanted to implement the most general categories first, so that your system would not fail to draw any symbol. Remember, it is correct to represent an object with its more general symbol, withing certain provisions. You can place an armor unit on the map without specifying the specific sub-type, and it's better than not drawing anything at all. So you think, "ok, no problem, I will just implement Draw()" for each kind of tactical symbol, and viola, my system is just as flexible as if I never touched inheritance.

    However, you cannot take advantage of virtual methods to buy you entire categories "for free" as it were. If you implement Draw as a virtual method of TacticalSymbol(), then its immediate children can take advantage of the default implementation for Draw(). Armor would supply a specific symbol, and all subcategories of Armor not yet defined would appear as that more general symbol. You can even omit implementations for a specific sub class, and it will just "bubble" up to the next least specific implementation up the hierarchy.

    There are further advantages, and I actually encountered this in my work. Say the Army is constantly adding new types of tactical symbols all the time. They all obey the same parsing scheme to identify them via a string. Each string just gets longer the more specific it is; two symbols with the same prefix guarantee that they share a common subtype. If I design my system with inheritance, my application will instantiate its type as its more general super class until I get around to adding a new sub class that represents it.

    Make sense? Sometimes, you really do want a "Is A" relationship between two types. In such cases, inheritance is the better tool, especially if the differences are largely additive. It is wasteful (and time consuming) to create classes that are combinations of everything they can do; you end up having to create a new type for every permutation of actions they are capable of. You provided an excellent example of when composition is desirable: when you want to favor flexibility regarding what a class "can do." When something really is a sub-type of another thing, however, inheritance is the better choice, and the one other programmers are going to expect you to use.

  24. As a noob Golang developer, I definitely relate to the 'composition' concept over typical OOP and inheritance! 👍🏾

  25. I would say that canDo vs howDos is a good way to define the difference. A vehicle CanMove. A car can move by action of an engine. An animal can poop. A snail can poop by way of breathing(friggin weird lol).

  26. Inheritance is only good to provide basic BSP or API functionality, where you sure do not want customer programmers to touch core functionality. -> Arbitration

  27. @Fun Fun Function how would you handle an object that changes during run-time. For example a character in a game becomes a wizard by picking up a staff. The character then picks up an axe and becomes a warrior. The character then drops the axe and can no longer fight? etc. Is it bad practice to assign and "un-assign"?

  28. 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 (:

  29. Great video :). Can you explain if we can override methods from the parent object like in inheritance. For example Object.assign{barker, pooper, superbarker}). Can superbarker first call bark method on barker and then call superbarker.bark. Thanks

  30. Best video I've watched so far on the topic. Also the only entertaining engineer on YouTube. Thank you for being you man 🙂

  31. Well, what youre actually describing in this video is not composition, but multiple inheritance.
    For a better explanation of what composition actually is, you can go to:

  32. I'm very sad about this video, and it was the moment I stop watching funfunfunction and stop following MPJ. Reason is I loved this idea and video initially, but later on I discovered video is completely false. There is no composition shown in here, but multiple inheritance, and MPJ as well his teacher the Snake oil Salsman(Eric Elliott) have no clue about the difference.

    reddit user MoTTs_ explain the difference quite nicely.

  33. 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

  34. Is it possible to replace the Object.assign () code with a spread operator instead? Doesn't that do the same exact thing?

    return {

  35. Okay. I am 3:09 into the video and I am praying to God you have many more because you are the perfect teacher. I just wiped a tear of joy. Literally.

    Edit: got to 4 min and my tear has been reimbursed for a tear of sadness, the video is in javascript:(

  36. is it possible to combine class composition with setters/getters? I am struggling figuring out how to do this or any resources that would tell me how to do that.

  37. I see the benefits of composition with a dynamic language like Javascript but I also contend that inheritance is more intuitive and less verbose. Sure, a hierarchy of classes may experience issues over time but how often does that really happen? My many years of development experience tells me it's rare. Thanks for the video!

  38. the gorilla-banana interpretation is from Joe Armstrong originally, who created to world's most well-paying programming language, Erlang.

  39. Thanks for the great video! I had this question in an interview the other day. Re: disliking inheritance… Is flexibility a downside? When I code, I try to decide very early on what something is and what something isn't. That way people won't shove random methods into my classes just because they can. It seems to me like inheritance, deciding what something will be in the future, at least has the advantage that in the future people will have a clear idea of how that thing works. Is this an issue? Or is it just a matter of clearly defining your composition methods (e.g. barker, killer, meower, cleaner, etc.)?

  40. How yould you do something like this in a "type safe" language like C#? You can't just add a bunch of methods/properties at runtime there, (Object.Assign) unless you use dynamic types or store them in a list/dictionary as object type, which would reduce performance and would kill one of the main points of a typed language.

  41. I can definitely see the pros of using composition but I do have a question though. Using composition instead of prototypal inheritance is alot more taxing on the memory is it not? Should I even care about that or should I just use composition as often as possible anyway?
    Thanks for doing all of these videos, I'm also from Sweden and I enjoy your videos alot so once again Tack så mycket! 🙂

  42. traits in Rust is the best execution of "composition over inheritance" baked into the programming language itself

  43. hahahaha, I do not use to write comments on videos. Yours is quite entertaining and funny. A murder robot dog hahahaha.

  44. Your Javascript example works more like a multiple inheritance than a composition pattern. In a compostion pattern you still have to write what to "inherit".

    obs: i think that languages that don't support multiple inheritance has a very important limitation

  45. Hi @mpjme, great video! I agree with your summary but if inheritance is such a bad pattern, why does React use classes?

  46. So i am going to create all my methods as separated functions and compose them … And then inherit the object if It makes sense and compose if it doesn’t ?

  47. Full composition is similar to writing in C in my opinion where you use struct to fully decoupled your data members, which is very flexible but can get out of hand too. Inheritance on the other hand can be limited and can be powerful if you encapsulate in design pattern methodology such as factory design pattern.

Leave a Reply

Your email address will not be published. Required fields are marked *