Mixin interfaces for Java?
In fact, when I think about Ruby, there are two main things I like there. These are closures and mixins. If both were added to Java 7, I would be more than pleased.
My idea for mixins would be pretty simple. No new syntax at all. Just use existing language feature - interfaces - and make them a little bit richer. The example mixin could look the following:
public interface Nameable {
private String name;
public String getName() {
return name;
}
public void String setName(String name) {
this.name = name;
}
}
You see? Nothing weird at the first look.
To use it, one would need to do the following:
public class Person implements Nameable {
public Person(String name) {
setName(name);
}
}
Again, nothing weird. All easy and nice. Of course, not for the javac compliler team, as they would need to do some hard work to implement it.
The basic idea for implementation would be the following - use a combination of an interface and anonymous inner class + delegation. So, in practice, the code generated by javac under the hood could be similar to this:
public interface Nameable {
public void getName();
public String setName();
}
public class Person implements Nameable {
// anonymous inner class part of a dirty trick
private Nameable __dirtyTrick = new Nameable() {
private String name;
public String getName() {
return name;
}
public void String setName(String name) {
this.name = name;
}
}
// delegation part of a dirty trick
public String getName() {
return __dirtyTrick.getName();
}
public void String setName(String name) {
__dirtyTrick.setName(name);
}
// normal code
public Person(String name) {
setName(name);
}
}
The hard part left to analyze is to figure out how to resolve "multiple inheritance"-like conflicts, communication of a mixin with a native class and all edge cases and consequences of this. But on the first sight, the idea seems to be workable to me.
Of course, these mixins are not dynamic as in Ruby - so you cannot inject or remove them from a class in runtime. But this would conflict a lot with static type checking, so we need to remember in what environment we are. For me, this is not a big problem.


