Tuesday, 3 September 2013

When to use Collections vs when to add extra function to a concrete subclass of a list?

When to use Collections vs when to add extra function to a concrete
subclass of a list?

Consider the following code to detect if linkedlist has a loop
public boolean hasLoop() {
Node<E> fast = first;
Node<E> slow = first;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (slow == fast) {
return true;
}
}
return false;
}
If Sun Microsystems were to add this functionality into Linkedlist.java,
how would they do it ? Note, Sun uses Node class as an internal detail (ie
private).
A few options that I can think of ( listed with disadvantages of each)
Static function 'hasLoop' in Linkedlist.java ? ( this is weird, because if
I want to do hasLoop for existing instance, I would call it
LinkedList.mergeSort(instance) rather than instance.mergeSort() )
Non-static function 'hasLoop' in Linkedlist.java? ( this would be weird
because some functions like sort belong to collections )
Subclass an Linkedlist.java and add new function 'hasLoop' ? ( this would
be weird because if I need to add another function like say
findIntersection, I would need to create another subclass )
Somehow use Collections and add a static method 'hasLoop(List)', and add
additional interfaces into LinkedList.java to make it somehow possible ? (
it would be ugly as Node is private class with internal implementation,
and ptr.next cannot be performed by collections. It would need some
setters to modify state like setNext() etc.)

No comments:

Post a Comment