Wednesday, November 16, 2011

An object oriented moment

I don't know why, but I think back on this a lot. Back in college I took a theory of object oriented programming course in java. In this class I experienced a break through that I account for most of my understanding of object oriented design and implementation. When I think about it now, it's such a simple concept, but at the time it was so difficult.

Here is the problem:

"How do you get a sequence to order the elements in reverse of their natural ordering? Write a program to demonstrate your technique. " - page 171, programming assignment 6, Java with Object-Oriented Programming, Second Edition, Paul S. Wang, Kent State University, ISBN 0-534-39276-8

The trick was not to implement a sort, not to iterate the items, just change the natural ordering of a sequence. I struggled with this for days, even visiting Professor Wang after class do work through it on the chalk board. "Can't I just output the list in reverse order?". Nope.

After while, for whatever reason, nobody told me, I didn't cheat, it simply dawned on me. Here is the summarized solution:
ArraySequence<SimpleDate> myseq = 
   new ArraySequence<SimpleDate>(new Comparator<SimpleDate>(){
      public int compare(SimpleDate d1, SimpleDate d2)
         { return d2.compareTo(d1); }
   }, 256); 

See it? The comparator passed returns d2 compared to d1 verses d1 compared to d2. That's it.

Well not completely. The ArraySequence object implements a quick sort. Within the partition, the compare will by default compare left to right. The reversal above switches the sort ordering. My solution is still live on the Kent State Computer Science department website here: sequence. All files were given except (again, we are not implementing the sort, just changing the ordering).

Such a powerful learning experience for me in terms of object oriented software. Interfaces, type parameters, plug compatibility, collections, sorting, etc. You don't rewrite the whole sort, you design the ordering to be pluggable. I don't know why, but I remember this moment often.

Special thanks to the Professor for not giving away the solution and letting me learn. If the links ever die here in this post, simply email me and I can pass along.

No comments:

Share on Twitter