Don't know how many people have rolled their own structured typing system in
plain old Java with generics, but I've been finding myself dragging the same
Pair class from one project to another and using it in some new and interesting
circumstances. Here's the basic gist of it (leaving out the obvious):
public class Pair<H, T>
{
public final H head;
public final T tail;
public Pair(H head, T tail) { ... }
public static <H, T> Pair<H, T> of(H head, T tail) { return new Pair<H,
T>(head, tail); }
public int hashCode() { ... }
public boolean equals(Object obj) { ... }
}
The above gives you essentially structured typing in Java. By nesting these
pairs, you can now create ad-hoc strongly typed object graphs and pass them
around. Gets a bit ugly fast when you see things like Pair<Foo, Pair<Bar,
Baz>>, but it does work. But here's an interesting side-effect that can be
used
as a 'good' pattern:
One of the problems in Java with defining new classes to represent data
structures is that we have to correctly implement hashCode and equals and too
often they're really easy to mess up in strange and subtle ways depending on
their intended use. So sometimes we resort to stuffing things into
collections,
seeing as collections implement that logic for a given, well, collection of
elements. But Java collections rely on a common parent type, so their use can
quickly devalue the type system and the power of generics. Aside from simply
passing around bare tuple-based object graphs, which adds a ton of bracket hell
to the code, it's possible to define data structure classes as extensions of
said tuple-based object graphs:
public class Person extends Pair<String, Pair<String, Integer>>
{
public Person(String first, String last, int age) { super(first,
Pair.of(last,
age)); }
public String getFirst() { return head; }
public String getLast() { return tail.head; }
public int getAge() { return tail.tail; }
}
I retain strong typing AND get to be assured of hashCode and equals correctness
(as long as Pair's implementations are right, which isn't hard to ensure using
Guava). I'm even being a good boy and making my data structure an immutable
bean.
Alexey
http://azinger.blogspot.com
http://bsheet.sourceforge.net
http://wcollage.sourceforge.net
____________________________________________________________________________________
No need to miss a message. Get email on-the-go
with Yahoo! Mail for Mobile. Get started.
http://mobile.yahoo.com/mail
--
You received this message because you are subscribed to the Google Groups "The
Java Posse" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/javaposse?hl=en.