This video by Udi Dahan made me rethink all if statements in my code:
In the video Udi uses the following deceptive simple looking requirement as an example:
“Disallow the user from buying products that are no longer available.”
Doh! This must be the easiest requirement I’ve ever seen. Let’s implement it…
Ok, when the user goes to the products page and we show a list of products, let’s add an extra check that only shows the items who are not deleted from our product catalog:
if(item.state== States.Deleted)
///Filter item from list
Ok, perfect. Problem solved! But wait, what if the user leaves the pages open for a while and in the mean time the product gets removed from the catalog, what happens if the user tries to add this product to his shopping cart? Ok, let’s add an extra check when the user tries to add an item to his cart:
if(item.state== States.Deleted)
///Show warning to user that product is no longer available
Ok, perfect. Problem solved! But wait, what if the user adds some products to his cart, leaves his cart open for a while and in the mean time the product gets removed from the catalog, what happens if the user tries to checkout his order? Ok, let’s add an extra check when the user tries to checkout his cart:
if(item.state== States.Deleted)
///Show warning to user that product is no longer available
Ok, perfect. Problem solved! But wait, what if the user spends a few minutes searching for his credit card during the checkout process and and in the mean time the product gets removed from the catalog, what happens if the user pays for his order?
Wait! Stop! Let’s break up here. It becomes obvious that there is always a moment where the if check is just to late.
The problem is that we end up with a business oriented eventual consistency problem that is hard to solve. Turns out that these kind of ‘if statements’ get better removed and replaced by long running processes that can impact the domain in multiple places.
To return to our example, the moment we set the IsDeleted flag to true for a product in our database, we’ll start a long running process that checks all active shopping carts, remove the deleted item from the carts and display the user a message when he returns to your website and opens his shopping cart: