Declaring Relations Between Model Instances

I’ve been playing with Xtext 1.0 the last three weeks. The editor support is most impressive. It’s one of those well balanced technologies that work “right” out of the box, offer lots of places where to hook in to tweak things.

The last few days, I’ve been chewing on a hard problem: Relations. I could to this:

class A {
}

class B {
    A parent 1:*;
}

Read: Instances of B have a field “parent” that references instances of A. There is a list in A with all instances of B where the field “parent” is that exact instance. In simple words, it’s a parent-child relation between A and B. For each B, there is always one A. Each A can have several B’s attached.

Or like this:

class A {
}

class B {
}

relation A children 1:* B parent;

The first solution avoids repetition but when looking at A, you will miss the fact that it has fields. It looks empty but the declaration in B adds a field. I don’t like it. While it might work in this case, how do you map N:M? Where do you declare a many-to-many relation? In A or in B? My guts say: Don’t do it.

The second solution is also flawed if less so. Here, both classes are empty. I have to look up the relations to see what else is going on. And I have to repeat information. I don’t like it.

Time to take a step back and sleep over it.

Fast forward over the weekend.

How about this:

class A {
}
parent of
class B {
}

One word: Intent. A construct in a programming language should clearly communicate intent. Which is one of the weak points in Java: It’s hard to express what you intend with Java. It’s not impossible but it takes years of experience to avoid the luring shortcuts.

So this new syntax clearly states what I want: A’s are parents of B’s. No repetition. No odd “1:*” which every reader has to decode. Which you can get wrong.

But what if A is parent of more classes? Simple:

class A { }
parent of {
    class B { } parent of class X { }
    class C { }
    ...
}

See? It nests. Let’s add tree-like structures to the mix:

tree class A { }
parent of {
    class B { } parent of class X { }
    class C { }
    ...
}

So A gets a parent-child relation with itself. One word says everything: Ownership. Cardinality. Field names.

My gut likes it. Listen to your guts. Especially when a simple solution tries to lure you into a shortcut.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 333 other followers