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

No comments:

Post a Comment