Thursday, April 29, 2010

Implementing a simple deterministic rule engine

The following is my experience of implementing a simple deterministic rule engine (if at all it can be called such) in JavaScript using Mozilla Rhino. This was part of the enterprise platform we are building in our company. We tried using Rete based JBoss Drools earlier but felt that a simpler deterministic rule engine would better suit our purpose.

The need for such a thing was due to various reasons:-
i) Rete based stateful rule engine was an overkill for our use case
ii) The non deterministic and asynchronous nature of Rete based rule engines makes debugging and testing very difficult (as pointed out by Martin Fowler)
iii) Most of the rules in our case were of the nature of validations or calculations which makes Rete an overkill
iv) A tailor made custom rule engine gives more flexibility and power
v) Our consumers (product developers) were not at ease with the programming style of traditional rule based approach


The approach went something like this:-
i) Enable server side scripting in JavaScript using Mozilla's Rhino engine
ii) Capture rules as metadata in the form of JavaScript statements (majority of them will be of the form if condition then action)
iii) Expose domain objects and other relevant APIs into the rule scripts at well defined lifecycle phases of entities (CREATE, UPDATE, DELETE, etc.)
iv) Execute the rule scripts within the context of domain objects and relevant APIs during the life cycle of domain objects (typically CRUD phases)
v) We also support a MANUAL context wherein developers can set relevant domain objects explicitly and invoke the rule engine

The beauty of LISP (and Clojure)

A couple of years ago, I accidentally came across the strange word Clojure, which I later came to know as a LISP style programming language on the JVM. At that point I was a total newbie to functional programming (and LISP), having spend most of my programming time on C, C++, Java, etc.

The first impression I had when looking at a medium size Clojure program was that of a mess of parenthesis. Why in the world would anybody want to write programs of this sort?

As many others, it took a while for me to truly appreciate the simplicity, elegance and beauty of functional programming in general and LISP in particular.

Clojure might have a popular future due to its clean way of handling concurrency and light weight threads (through Software Transactional Memories aka STM)

Hats off to John McCarthy for creating LISP and Rich Hickey for creating Clojure.

Handling Spring ApplicationContext events in Spring DM based OSGi environment

Listening for and handling Spring ApplicationContext events in a Spring DM setup needs needs two steps:

1) Implement a class for the interface org.springframework.osgi.context.event.OsgiBundleApplicationContextListener
import org.osgi.framework.Bundle;
import org.springframework.context.ApplicationContext;
import org.springframework.osgi.context.event.OsgiBundleApplicationContextEvent;
import org.springframework.osgi.context.event.OsgiBundleApplicationContextListener;
import org.springframework.osgi.context.event.OsgiBundleContextClosedEvent;
import org.springframework.osgi.context.event.OsgiBundleContextRefreshedEvent;

public class BundleApplicationContextTracker implements OsgiBundleApplicationContextListener {
public void onOsgiApplicationEvent(OsgiBundleApplicationContextEvent event) {
if(event instanceof OsgiBundleContextRefreshedEvent) {
// handle bundle start
} else if(event instanceof OsgiBundleContextClosedEvent) {
// handle bundle close
}
}
}

2) Expose the above class as an OSGi service by putting the following entries in Spring beans-config.xml

<beans:bean id="bundleContextTracker" class="org.mypackage.BundleApplicationContextTracker" scope="singleton"/>
<osgi:service id="bundleContextTrackerOSGi" ref="bundleContextTracker" interface="org.springframework.osgi.context.event.OsgiBundleApplicationContextListener"/>

Capitalism and environmental damage

One of the general principles on which Capitalist economy and market (particularly the corporate world), works is "produce more, sell more; buy more, consume more". This is inevitable as increased revenue/profit is the yardstick by which all corporates measure their performance. In the long run this can happen only if the seller produce MORE and the buyer consumes MORE. Advertisements do a fairly good job of making consumers believe that they are lesser if they don't have certain goods (even when they really don't need it).

MORE seams to be the war cry of the majority of us living under Capitalism (both producer and consumer). But where is the MORE coming from, what is its source? Clearly it cannot come out of thin air. No doubt, we keep on improving our business models , processes and technology . But they alone can't create this MORE. There is something more fundamental than our technical innovation, free market and global economy that makes this possible. What does it cost for this so called MORE to be produced and consumed? The short answer is NATURE.

Most of the gains of modern human societies comes at the cost of NATURE. Scientists estimate that the environmental damage done over the past few centuries by our industrial modes of production is almost irreparable. Most of our energy hungry economies today cannot function without adding more CO2 to the atmosphere or by putting more holes in "Ozone Layer".

The Capitalist cry for MORE will continue to increase the damage.It forces individuals and societies to push nature to its limits. Day after day we as groups and individuals ask more and more from nature. Our bore-wells and oil wells gets deeper, our forests gets thinner, species of flora & fona gets fewer in number. Nature though pushed to its limits, somehow meets our demands. But, how far will it go on?

A day may come when NATURE turns back on us and tells , "I have given all that I could, I have nothing more to give". Many environmentalists feel that such a day may only be a few decades or a few centuries down the line.

Is this (the greed for MORE) a fundamental contradiction within Capitalism, a contradiction much more severe than the "Class conflict/contradiction" of Marxist analysis? This problem raises more questions. Will our greed for MORE stop at some limit? Do we need to look for alternative political systems? If not Capitalism, what?

Though very young, Capitalism has been by far the most stable and most successful political structure in the history of mankind. Thanks to the scientific revolution that developed almost in parallel with itself, Capitalism has made life better for a large number of people. It has fed and clothed more people than any other political system.

Communism/Marxism offered an alternate system that promised to overcome the inherent faults of Capitalism. But living in a time after the collapse of USSR and the other Communist giant China getting capitalized more and more, we can definitely say that Capitalism is the only major political system in the world today. (Exceptions like Communist Cuba, Dictatorships, Kingdoms, etc. could be very well ignored.)

Whatever be its demerits, Capitalism has one virtue that almost all other political systems in History lacked. It has a self corrective factor within itself. And that is what has made it the most successful of all political systems. The solution for environmental crisis and other problems due to human greed cannot be alternate political systems (be it economic/fascist/theocratic) or revolutions. Any sensible solution has to be more practical and pragmatic.

Though an over simplification, we could very well say that Capitalism like any other human enterprise is a tool that we created for ourselves. Its not an uncontrollable giant that controls our fate (as the historicist would see it). And any tool could be wisely used or abused. More than a change of tools, what we may need is to learn the tools wisely.

The long term solution would be DISCIPLINE. We need to learn as individuals, societies and nations to restrain our GREED.