Declarative programming deals with what is, as opposed with the how to normally encountered in imperative programming languages. Drools relaxes the bias toward a unidirectional logical flow and enables a much more declarative approach to programming.
This is useful in complex fact-based evaluations and in creating nondeterministic languages, where a single what is can be used to solve multiple problems with different how to components.
Declarative rules typically take the form as follows:
The rules declare by way of the condition what should occur, but do not specify the procedure for actually testing the conditions. For example, an imperative method for ensuring you have an umbrella if it is raining would be:
The above could also be represented by two declarative rules:
Given declarative rules, the knowledge that it is raining could produce two
courses of action:
- You already have an umbrella, perhaps because you always carry one, in
which case, you're ready.
- You don't have an umbrella, so you go get one from the closet.
This allows you to come by the knowledge that its raining in more than one way, and respond to that knowledge in the most appropriate fashion, depending on other available knowledge. For instance, if you know you're going to be away from the house and that it is likely to rain, you can add another rule to the ones you specified above:
At this point, you only need to go get an umbrella if you know you don't already have an umbrella, and either that it is raining, or that it might rain later while you're away from the house. If you were to write that all out in procedural code, it'd quickly get tangled and complex. Imperative logic helps us decompose complex decisions into mind-sized pieces.