Sunday, March 21, 2010

Generic Programming in C++

Last week I was working on how does the templates can solve some problems which can avoid to write repeated code. Basically I was trying to apply principles which Generative Programming tells (In a very beautiful way indeed).
One of the few principles it states that about domain engineering. How for a particular domain, code can be inside common repository.
The easy part is code can be written prety easily using templates. But all this depends on projects that you are doing. Most of the time code gets written based on requirements of a concrete product. I feel in those environments writing domain based code is not possible. (Like STL can't be written with a particular project in time).
To write the code which can be used in a domain there should be two approched one is vertical and horizontol.
Vertical approach is required when code is written for a product and in those places generalization can be done. There you'll see the plethora of libraries being written which solve various purpose.
More difficult is to use horizontol approach. Here the true generic programming takes place.
I think this is similar to data mining: In data mining data is analyzed to get the patterns hidden in data. Similarly for "code mining" its required to do code analysis and find patterns in code and help in writing code which can be used across similar product lines.

Take an example: Take a model of trying to route a message based on a configured policy.
Now for a router (IP Layer) this could be based on IP tables for an HTTP server it should be based on DNS. (Network Layer)
If you see the code is almost easy and should be written like below so that each prodfuct can be used it independently.

template typename Message,
class MessageRouter
{
bool operator()(Message & message,RoutingPolicy & routingPolicy)
{
RoutingPolicy::Iterator itr = routingPolicy.getFirstPolicy();
for (;itr != routingPolicy.end();++itr)
{
if (itr->route(message))
{
return true;
}
}

return false;
}
};

This code is a simplification. But we can see the principles here. The same code code is repeated across the IP layer and application layer across TCP/IP leyer.

No comments:

Post a Comment