Process to pass from problem to code. How did you learn?

I go via the test-driven approach.

1. I write down (on paper or plain text editor) a list of tests or specification that would satisfy the needs of the problem.

- simple calculations (no discounts and concessions) with:
    - single item
    - two items
    - maximum number of items that doesn't have a discount
- calculate for discounts based on number of items
    - buying 10 items gives you a 5% discount
    - buying 15 items gives you a 7% discount
    - etc.
- calculate based on hourly rates
    - calculate morning rates
    - calculate afternoon rates
    - calculate evening rates
    - calculate midnight rates
- calculate based on buyer's age
    - children
    - adults
    - seniors
- calculate based on combinations
    - buying 10 items in the afternoon

2. Look for the items that I think would be the easiest to implement and write a test for it. E.g single items looks easy

The sample using Nunit and C#.

[Test] public void SingleItems()
{
    Assert.AreEqual(5, GetPrice(5, 1));
}

Implement that using:

public decimal GetPrice(decimal amount, int quantity)
{
    return amount * quantity; // easy!
}

Then move on to the two items.

[Test]
public void TwoItemsItems()
{
    Assert.AreEqual(10, GetPrice(5, 2));
}

The implementation still passes the test so move on to the next test.

3. Be always on the lookout for duplication and remove it. You are done when all the tests pass and you can no longer think of any test.

This doesn’t guarantee that you will create the most efficient algorithm, but as long as you know what to test for and it all passes, it will guarantee that you are getting the right answers.

Leave a Comment