This essay says that inheritance is harmful and if possible you should “ban inheritance completely”. You see these arguments a lot, as well as things like “prefer composition to inheritance”. A lot of these arguments argue that in practice inheritance has problems. But they don’t preclude inheritance working in another context, maybe with a better language syntax. And it doesn’t explain why inheritance became so popular in the first place. I want to explore what’s fundamentally challenging about inheritance and why we all use it anyway.

  • Kacarott@feddit.de
    link
    fedilink
    English
    arrow-up
    2
    ·
    edit-2
    7 months ago

    Well what is an enum except a chain of X | Y | Z | .... An enum can be any of its variants, and therefore the set of its possible values are just all possibilities of its variants added together.

    Consider this enum:

    enum Foo {
      A,
      B(bool),
    }
    

    The possible values for A are just one: A. The possible values for B are B( true ) and B( false ). So the total possible values for Foo are simply these sets combined: A or B( true ) or B( false ).

    As for product types, what it is the product is, is still the same: the sets of possible values. Consider the possible values for the product of A and B. For every possible value of A, a value could be made by matching it with any possible value of B (so, multiplication). If there are 3 possible values of A, and two possible values of B, then the total number of possible combinations of these for the product type is 6.

    In your example, Dog is a product of u8, another u8, and String. If you decide to add a Boolean field to this type, accordingly the size of the set of options would double, because for every possible Dog you currently have, two possibilities would be created, one with a true and one with a false.

    As for your last question, some languages might use x as a product type syntax, but because tuples and structs are inherently product types, most languages use those as Syntax. For example in Haskell the product type of Dog and Cat would be written as (Dog, Cat).