What are the alternatives to "overriding a method" when using composition instead of inheritance?

Posted by Sebastien Diot on Programmers See other posts from Programmers or by Sebastien Diot
Published on 2012-05-31T11:02:59Z Indexed on 2012/05/31 16:50 UTC
Read the original article Hit count: 422

Filed under:

If we should favor composition over inheritance, the data part of it is clear, at least for me.

What I don't have a clear solution to is how overwriting methods, or simply implementing them if they are defined in a pure virtual form, should be implemented.

An obvious way is to wrap the instance representing the base-class into the instance representing the sub-class. But the major downsides of this are that if you have say 10 methods, and you want to override a single one, you still have to delegate every other methods anyway. And if there were several layers of inheritance, you have now several layers of wrapping, which becomes less and less efficient. Also, this only solve the problem of the object "client"; when another object calls the top wrapper, things happen like in inheritance. But when a method of the deepest instance, the base class, calls it's own methods that have been wrapped and modified, the wrapping has no effect: the call is performed by it's own method, instead of by the highest wrapper.

One extreme alternative that would solve those problems would be to have one instance per method. You only wrap methods that you want to overwrite, so there is no pointless delegation. But now you end up with an incredible amount of classes and object instance, which will have a negative effect on memory usage, and this will require a lot more coding too.

So, are there alternatives (preferably alternatives that can be used in Java), that:

  • Do not result in many levels of pointless delegation without any changes.
  • Make sure that not only the client of an object, but also all the code of the object itself, is aware of which implementation of method should be called.
  • Does not result in an explosion of classes and instances.
  • Ideally puts the extra memory overhead that is required at the "class"/"particular composition" level (static if you will), rather than having every object pay the memory overhead of composition.

My feeling tells me that the instance representing the base class should be at the "top" of the stack/layers so it receives calls directly, and can process them directly too if they are not overwritten. But I don't know how to do it that way.

© Programmers or respective owner

Related posts about composition