Home

Find equivalent definitions to find a simple implementation

Reformulating definitions can help you  find a simple implementation. What do I mean?

Let's illustrate with an example from probability. Given the chance of winning the lottery is 0.1%, what is the chance of winning the lottery at least once if I play 10 times?

There is a complicated way to calculate this probability or a simpler way if you reformulate the question:

  • The probability of winning at least once = 1 - the probability of never winning

Calculating the probability of never winning is simple. You need to lose every time you play. That's 99.9%^10. Therefore:

  • The probability of winning at least once = 1 - 99.9%^10

You can apply this principle in programming as well! I had to write a method  that returned only the orders for which the products were in stock. If an order had a Gameboy color and there was no Gameboy color in stock I needed to exclude it.

Redefining the selection criterium made it very easy to implement:

  • Original selection criterium: order with products in stock
  • Equivalent selection criterium: order without any products that are out of stock

This second selection criterium was much easier to implement. The solution in MongoDB:

db.orders.find({
 'order_lines.product_id' : {$nin: get_ids_of_products_out_of_stock()}
})