The shopping cart rule engine DSL

time to read 1 min | 144 words

As the final example in the book, I am showing off a DSL for processing a shopping cart. Here is how it looks like:

behavior of preferred_customer

upon bad_credit:
	authorize_funds cart.Total * 0.5,  "For preferred customers we only authorize half the amount"

upon cart_update:
	when cart.Total > 1000:
  		add_cart_discount 5, "Preferred members gets 5% discount for orders over 1,000$"

And this:

behavior of default_customer

upon bad_credit:
      authorize_funds cart.Total,  "We require full authorization of the amount in low credit rating scenarios"

Where we defined preferred customer and default customer as:

define preferred_customer:
	customer.TotalPurchaseAmount > 5000
define default_customer:
	customer.TotalPurchaseAmount <= 5000

The implementation is surprisingly easy, and I was able to walk through the reasoning for this implementation rather than the usual when [condition] in a way that I hope would make sense.

You can look at the implementation here: