Shopping Cart Kata

Writing code is much like playing music, or roller derby. When you go into work, it’s like a concert or a bout. Can you imagine what a concert would be like if none of the musicians practiced? Or the carnage at a game if none of the skaters trained? Yet the majority of developers do just that each and every day.

Remember this scene from Karate Kid? Where poor Daniel Son is getting fed up of sanding the floor, waxing cars and painting fences:

I’m sure musicians get bored of endlessly practicing their scales, and I know that the New Wheeled Order lads get sick to death of doing wall drills… The purpose is to teach muscle memory. What we do every day, solving problems (our fight situation), is hard enough without having to think about your techniques. We owe it to our employers and to our craft not to be learning these skills on the job.

So I use coding katas as my scales. I’ve included my favourite, the Checkout Kata. It lends itself quite well as a simple enough problem, but with enough challenge to lend itself to being test driven and turning into some sort of nice OO design.

Your first few attempts at this should be with the sole aim of getting to know the problem. Try attacking it in your favourite language, in your preferred style. Spend no more than 40 mins on it. THE POINT IS NOT TO FINISH THE PROBLEM! After 40 mins I want you to throw away everything you’ve done and start over. Hindsight is a wonderful thing. If you become obsessed with finishing this, you’ll miss the point of LEARNING. Once you’ve thrown everything away and started again, you might spot something you didn’t think of before, you’ll find the code takes a completely different path and you’ll be learning from your previous mistakes that you didn’t even know were mistakes.

As you get more confident with the problem, try using it to learn something new. Now the problem is a non-issue, you need a new challenge. How about TDD? Pairing? A design pattern? Tell Don’t Ask… Even a new language.

Give it a go, and let me know your thought and experiences. I’ll try to come back and do a follow up post.

Checkout Kata

Implement the code for a supermarket checkout that calculates the total price of a number of items. Goods are priced individually, however there are weekly special offers for when multiple items are bought. For example “Apples are 50 each or 3 for 130”.

Weekly offers change frequently.

SKUUnit PriceSpecial Offer

A99 50 3 for 130
B15 30 2 for 45
C40 60
T34 99

The checkout accepts the items in any order, so that if we scan a pack of Biscuits, an apple and another pack of biscuits, we’ll recognise two packs of biscuits and apply the discount of 2 for 45.

suggested interfaces (feel free to write your own!):

Javascript

var Checkout = function(){
  function total(){
  }
  
  function scan(item){
  }

  return {
    scan: scan,
    total: total
  };
};

Ruby

class Checkout
  def total
  end

  def scan(item)
  end
end