2 pointsby sneakyPad13 hours ago2 comments
  • MORPHOICES12 hours ago
    I remember reading this thing about programming where people talk about behavior instead of inheritance. It stuck with me because Ive dealt with some code that got messy fast. ~

    Like, when do you actually pick behavior over inheritance in stuff youre writing? I mean, the question is out there, asking for real experiences.

    For me, inheritance seemed okay at first, you know, building these trees that looked neat. But then they turn rigid, and youre stuck. It burns you a few times.

    Shifting to behavior feels better. Its not about what the object is exactly, but what it can do. That changes things.

    Protocols help make that clear, or interfaces in different languages. The idea is, if it acts like it can do the thing, then it works. Kind of like the duck thing, if it quacks like a duck.

    I have this rough idea in my head. Use inheritance when you want to share the actual code implementation. But for protocols, its more about what everyone expects, the shared behaviors.

    Still, Im not totally sure where to draw the line between them. It gets a bit fuzzy.

    How do others figure it out? What are the signs that inheritance is going to cause problems down the road, like aging badly?

    • sneakyPad11 hours ago
      Those are some very good thoughts and questions. As I tried to touch on in the article, the own mental model has to shift slightly away from the typical inheritance tree. I have built products in which I use inheritance over behaviour, and it was fine. However, I also experienced that it does make the code tightly coupled, and this leads also to what you describe, as it got messy fast. All of a sudden, I added edge cases here and there. Certainly, the abstraction could have been improved, but the point remains. It would have aged even worse with multiple devs on the product and different libraries. Large inheritance trees tend to become brittle. That was my point with the machine learning models. With behaviour and static protocols, it has been so much easier to integrate different approaches.

      Having said that, I read (I think also from Luciana Ramalho) that inheritance can make sense when developing a library/package itself. Nevertheless, I would try to use static protocols as long as it seems possible. Inheritance for code reuse is an implementation detail. It can often be replaced by composition and delegation.

      I hope this gives you a bit more context to the article and idea of using behaviour over inheritance.

  • go2613 hours ago
    To use it:

      from typing import Protocol
    
    s/new //
    • sneakyPad11 hours ago
      Good catch! Thanks a lot, I updated the snippets.