Monday, 23 March 2009

In abstract

After hearing the story of the Black Swan it is impossible not to feel (at least slightly) smug.   As programmers, however, we often have to deal with objects from the 'real world', (which to remind people that we are sort-of scientists,  we call 'the problem domain', or if we're sitting opposite a logician: the 'domain of discourse').

Nomenclature aside, it is often our task to build a model of the real world, a world about which we do not have complete information.   A model (my CS inspired definition) is really just the result of taking salient features of the real world and representing them in a way that is suitable for a computer to do something useful with.  If you hang around with enough programmers for long enough the word 'abstraction' will rear its head, which (at least on my blog) is a synonym for the act of modelling.

Modelling (or abstraction) is favoured by programmers because it allows great swathes of the real world to be captured by very little code.  Imagine you are building a till/checkout system for a supermarket, which to reduce the size of this post, contains only 3 items:
  1. bread
  2. milk 
  3. the guardian
Let us implement this as naively as possible:
  • scan bread, add £1.10 to the bill, display total on screen
  • scan milk, add £0.90 to the bill, display total on screen
  • scan the guardian, add £0.70 to the bill, display total on screen
The problem with this code is that we're treating every item with too much reverence.  For every extra item we add to the shop (a fine cheese for example) we'd have to add some more code.   We don't really care about the specifics of each item, all we care about is their price.   By treating the goods of the supermarket as  'priced products' we can simplify the logic:  (although unrealistic, we will assume the price is encoded in the barcode):
  • scan priced product X, convert barcode to price, display total.
If you've ever received junk mail you can be sure it was generated by treating all 'customers' as 'named addressable units', not as the unique individuals all my readers inevitably are.  Back to our example, the shopkeeper has been adding extra products to his store without need to update any software until one day he decides to add a 'pick and mix' counter.  His 'pick and mix' bags have a barcode, but the price is determined by the bag's weight, not just the barcode.  

To fix this we have to add an exception or specialisation:
  • if product is 'pick and mix' weigh product, calculate price times weight, display total
  • else scan priced product X, convert barcode to price, display total 
I'd hoped this post would lead nicely into an overview of default reasoning, where we accept a default argument (the price of an item is determined by its barcode) unless we have further information (the item 'pick and mix' and should be weighed) but I have had more fun writing about a fictitious supermarket.   Sorry!

0 comments:

Post a Comment