|
Re: Traits for Java
|
Posted: Jun 7, 2010 10:00 AM
|
|
Hello Howard! I like the idea of having traits in Java. I add some of my thoughts.
What I see as the major advantage is that we would be able to compose complex classes from individual traits (and desired implementations of those traits). Using the List example, sorting is one trait, reversing the list would be another and shuffling yet another. For each of these traits there could be different implementations (quicksort, heapsort, mergesort, bubblesort, ...). The user may desire any combination of traits and their implementations. Here is how one could define two implementations of a sortable list: an array list with quicksort and a linked list with bubble sort.
interface SortableList<E> extends List<E> {
public void sort();
}
interface QuickSortableList<E> extends SortableList<E> {
@Override
public void sort() {
// implement quicksort on top of List methods
}
}
interface BubbleSortableList<E> extends SortableList<E> {
@Override
public void sort() {
// implement bubblesort on top of List methods
}
}
class QuickSortableArrayList<E> extends ArrayList<E> implements QuickSortableList<E> {
// no code except constructors needed
}
class BubbleSortableLinkedList<E> extends LinkedList<E> implements BubbleSortableList<E> {
// no code except constructors needed
}
It would be even more flexible if there was some syntax for automatic definition of the "composite" class, i.e. no explicit definitions of QuickSortableArrayList and BubbleSortableLinkedList would be necessary. For example, like this:
SortableList<E> list1 = new ArrayList<E>{QuickSortableList<E>}();
SortableList<E> list2 = new LinkedList<E>{BubbleSortableList<E>}();
(In the braces is the list of traits to implement. Constructors are "inherited" from the superclass.)
To make traits even more usable, the same automatic class/interface generation could be supported in variable/field declaration.
List<E>{SortableList<E>, ShufflingList<E>} list = ...
Such synthetic class would be generated either at compile time or on its first use at runtime. An important property that should be guaranteed would be that a class with some traits would be assignable from a class that implements a superset of its traits, as in
List<E>{SortableList<E>, ShufflingList<E>} list1;
List<E>{SortableList<E>, ReversibleList<E>, ShufflingList<E>} list2 = ...;
list1 = list2;
(Not sure how feasible this would be to implement.)
|
|