First off, I know next to nothing about language theory, and I barely know any other languages except Java, but I had an idea that I think would be cool, but I need you guys to tell me:
a: why it sucks
b: how language x has had that for years
c: how my mind sucks
d: all of the above
The idea would give composition the same ease of code reuse that extends does.
So if you had a class like this:
public interface A { public void methodInA(); }
And then you had a class like this:
public class B { private composed A; public B() { // construct A within constructor } }
You would then be able to do this:
B myB = new B(); myB.methodInA();
Without having to add in the delegation in B’s class. But you could also do the same as with inheritance, ie:
@Overrides public void methodInA(){ // B's own delegation method }
Disadvantages include:
- methods are hidden in the source code, making it less obvious where the call is coming from, but this is also the case with
extends - if composed fields share the same method signature there needs to be a conflict resolved (how do conflicting interfaces solve this?)
- if you wanted to have several composed fields of the same type, there would be an obvious conflict for which field to delegate to
- probably 100 other things I’ve not thought of
Like I say, I’m obviously no language theorist, and I haven’t spent ages thinking about it, the idea just popped in my head and I wanted to know how wrong I am. I just think it would be kind of cool.
I think if you restricted it such that a class could only use this feature to compose a single class it would be somewhat useful and would avoid a lot of the headaches that are being discussed.
Personally I hate inheritance of concrete classes. I’m a big proponent of Item 14 from Bloch’s Effective Java, Favor composition over inheritence. I think that something like this would make it a little easier to implement the idiom he recommends in that item.
Honestly, if you really knew what you were doing I’ll bet you could write a compiler annotation that would handle this. So assuming you had a class Bar that implemented the interface IBar, your class would look like this:
Then during compilation Foo could be made to implement IBar and any of the methods on that interface that weren’t already implemented by Foo would end up being generated to look like this:
As mentioned above you would want to make the restriction that only one field per class could use this annotation. If multiple fields had this annotation you’d probably want to throw a compilation error. Alternatively you could figure out a way to encode some sort of precedence model into the parameters passed to it.
Now that I’ve written this out that seems kinda cool. Maybe I’ll play around with it next week. I’ll update this if I manage to figure anything out.