Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

My understanding is that composition can be changed dynamically whereas inheritance cannot. It has always seemed to me like composition is more flexible.

To give concrete examples: using composition, if instance A has a B, then at runtime you can replace the pointer to the B with a pointer to a C such that now A has a C. You basically change the type of A by changing where messages get sent / delegated.

With inheritance, you'd have B is an A and C is an A, and the relationships here are static unless you start messing around with reflection and dynamic class loading and stuff.

The tradeoff for the flexibility of composition is more verbose code, I think.



Dynamic inheritance is not unthinkable, I've used it in my languages before (or see research languages like Cecil). Of course, you can do this easily in dynamic languages like ruby.


Actually, can you really do dynamic inheritance in ruby? I don't _think_ so. There are ways to apply inheritance dynamically at runtime of course (including with module mix-ins, which are basically just inheritance even though ruby pretends it isn't), but I don't think you can _undo_ inheritance at runtime.

You can easily simulate dynamic inheritance in ruby.... with composition, using delegate-like patterns.


but I don't think you can _undo_ inheritance at runtime

I'd be surprised if you couldn't do it in Ruby. You certainly can do it in Perl because it uses a package (class) variable called @ISA for it's inheritance lookup.

And because package variables are dynamically scoped you can do this:

  {
    # remove everything except father from inheritance
    local @Some::Class:ISA = $Some::Class::ISA[-1];

    $some_object->foo;   # finds father foo() only
  }
  
  $some_object->foo;     # runs first foo() found in inheritance




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: