Monday, December 15, 2008

Composite Oriented Programming

Ok, so I found a new buzzword; Composite Oriented Programming. I first heard it from Thomas Biskup. He wrote about it on his JADE-blog, here. From there I started reading about COP on qi4j.org. I haven't completely understood it, but so far it seems to be quite nice buzzword.

So I wrote a small hello world sample in D using templates. Got it working after a while with the help of downs and Bill Baxter, on #D and D.learn respectively.

You can find the code here.

I'll go over it here now.

First we have a template to hold out data, namely helloStr:

public template HelloData
{
private char[] helloStr;
}

Next we define the action or function for the whole composite. I don't remember what this is in COP-speak.

public interface HelloSpeech
{
public char[] sayHello();
}

Then we implement the above function in HelloSpeaker.

public template HelloSpeaker
{
mixin HelloData;

public char[] sayHello()
{
return helloStr;
}
}

So we mixin the data template, so we can return the helloStr from sayHello. Notice that we don't need to import the actual interface for sayHello.

Then we will create the actual composite.

public class HelloWorld : HelloSpeech
{
mixin HelloSpeaker;

public this()
{
helloStr = "Hello, World!";
}
}

Now we have a concrete class that implements HelloSpeech. If you look at the code here, you notice that we've had to import the HelloData module. This is as far as I can see the only downside so far.

We have now nicely removed the implementation for sayHello to their own modules. This is a very small example, but I can see it to be quite useful with bigger systems and with more interfaces.

Now just add an interface for setting the value for helloStr and creating an implementation for it, then this would be complete. The helloStr could be hidden completely behind a getter/setter-pair.