An Extract and Override Exercise
Extract And Override Solution
If you want to take a look at our solution, here you go!
We've changed accountId to be protected.And we've extracted two awkward parts of methods:
public class Order
{
public void Add(LineItem item)
{
items.Add(item);
netTotal = netTotal.Add(item.ExtendedAmount);
weight = weight.Add(item.ExtendedWeight);
ReserveProduct(item);
} protected virtual void ReserveProduct(LineItem item)
{
InventoryControl.Get().ReserveProduct(orderId, item.Sku, item.Quantity);
} public virtual string OrderId
{
get
{
if (orderId == null)
orderId = GetOrderIdFromGenerator();
return orderId;
}
} protected virtual String GetOrderIdFromGenerator()
{
return IdGenerator.GetOrderId(accountId);
}
…
}
We created
TestableOrder
right in the OrderTest
file, and overrode the two awkward parts.
public class OrderTest
{
private class TestableOrder : Order
{
public TestableOrder(string accountId) : base(accountId)
{
} protected override string GetOrderIdFromGenerator()
{
return accountId + ":10001";
} protected override void ReserveProduct(LineItem item)
{
}
}
…
}
public class OrderTest
{
[SetUp]
protected void SetUp()
{
largeProduct = new Product("SKU001", "Large Widget", new Money(123.00m), new Weight(6.00m));
smallProduct = new Product("SKU002", "Small Widget", new Money(4.56m), new Weight(0.10m));
oneLarge = new LineItem(largeProduct, 1);
oneSmall = new LineItem(smallProduct, 1);
threeSmall = new LineItem(smallProduct, 3);
order = new TestableOrder("ACCOUNTID");
}
…
}
You can download our solution here:
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |