Created
May 24, 2011 00:51
-
-
Save mattflo/987947 to your computer and use it in GitHub Desktop.
The outcomes of my repeated vending machine kata adventures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using NSpec; | |
namespace VendingMachineKata | |
{ | |
class describe_VendingMachine : nspec | |
{ | |
VendingMachine machine; | |
string firstSnickersVend; | |
string secondSnickersVend; | |
void an_empty_machine() | |
{ | |
before = () => machine = new VendingMachine(); | |
specify = () => machine.Vend("A1").Is("not in stock"); | |
context["doritos are stocked in A1, and 2 snickers in A2"] = () => | |
{ | |
before = () => | |
{ | |
machine.Stock("doritos", "A1"); | |
machine.Stock("snickers", "A2"); | |
machine.Stock("snickers", "A2"); | |
}; | |
specify = () => machine.Vend("A1").Is("doritos"); | |
context["snickers are vended"] = () => | |
{ | |
before = () => firstSnickersVend = machine.Vend("A2"); | |
specify = () => firstSnickersVend.Is("snickers"); | |
context["another snickers is vended"] = () => | |
{ | |
before = () => secondSnickersVend = machine.Vend("A2"); | |
specify = () => secondSnickersVend.Is("snickers"); | |
specify = () => machine.Vend("A2").Is("not in stock"); | |
}; | |
}; | |
}; | |
} | |
} | |
class VendingMachine | |
{ | |
public VendingMachine() | |
{ | |
stock = new StockDictionary<string, Item>(); | |
} | |
public void Stock(string name, string slot) | |
{ | |
stock.AddStock(slot, () => new Item(name)); | |
} | |
public string Vend(string slot) | |
{ | |
return stock.ContainsKey(slot) ? stock.Get(slot).Name : "not in stock"; | |
} | |
StockDictionary<string, Item> stock; | |
} | |
class StockDictionary<T, U> : Dictionary<T, U> where U : IQuantity | |
{ | |
public void AddStock(T key, Func<U> value) | |
{ | |
if (!ContainsKey(key)) | |
Add(key, value()); | |
else | |
this[key].Quantity++; | |
} | |
public U Get(T slot) | |
{ | |
var item = this[slot]; | |
if (item.Quantity == 1) | |
Remove(slot); | |
else | |
item.Quantity--; | |
return item; | |
} | |
} | |
class Item : IQuantity | |
{ | |
public Item(string name) | |
{ | |
Name = name; | |
Quantity = 1; | |
} | |
public string Name { get; set; } | |
public int Quantity { get; set; } | |
} | |
interface IQuantity | |
{ | |
int Quantity { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment