Tuesday, March 8, 2011

Solving the supermarket coding kata using TDD – Part 3

The supermarket coding kata problem domain deals with the scenario of pricing goods at supermarkets. The scenario handles situations like.
Items in supermarket have simple prices, e.g. One Gatorade for $4.5. Other items may have complex prices like three for dollar or $3 for one pound etc.
This is the last in the 3 part series of our implementation of the above mentioned problem. We’ll be implementing the checkout list and associated test cases.
The checkout list contains item details with the item and the quantity for each item purchased. The total cost of the checkout list is calculated by aggregating the cost of each item details in the list.
[TestMethod]
public void checkoutlist_contains_of_multiple_itemdetails_for_each_item_and_quantity_of_purchased()
{
    CheckoutList checkoutList = new CheckoutList();

    Item kellogs = new Item("Kellogs corn flakes");
    UnitPricingStrategy kellogsPricingStrategy = new UnitPricingStrategy(3.5M);
    kellogs.SetPricingStrategy(kellogsPricingStrategy);

    ItemDetail itemDetail = new ItemDetail(kellogs, 3);

    checkoutList.Add(itemDetail);
    decimal totalPrice = checkoutList.GetTotalPrice();
    Assert.AreEqual(totalPrice, kellogs.GetPrice() * 3);
}

Implementation
public class ItemDetail
{
    private Item _item;
    private int _quantity;

    public ItemDetail(Item item, int quantity)
    {
        this._item = item;
        this._quantity = quantity;
    }

    public decimal GetCost()
    {
        return _item.GetPrice() * _quantity;
    }
}

public class CheckoutList
{
    public CheckoutList()
    {
        _itemDetails = new List<ItemDetail>();
    }

    public void Add(ItemDetail itemDetail)
    {
        _itemDetails.Add(itemDetail);
    }

    List<ItemDetail> _itemDetails;

    public decimal GetTotalPrice()
    {
        decimal totalPrice = 0.0M;
        foreach (var itemDetail in _itemDetails)
            totalPrice += itemDetail.GetCost();

        return totalPrice;
    }
}

No comments: