Case Study: Refactoring Strategy

Classic Strategy


In [2]:
from abc import ABC, abstractmethod
from collections import namedtuple

In [3]:
Customer = namedtuple('Customer', 'name fidelity')

In [4]:
class LineItem:
    
    def __init__(self, product, quantity, price):
        self.product = product
        self.quantity = quantity
        self.price = price
        
    def total(self):
        return self.price * self.quantity

In [18]:
class Order: # The Context
    
    def __init__(self, customer, cart, promotion=None):
        self.customer = customer
        self.cart = list(cart)
        self.promotion = promotion
        
    def total(self):
        if not hasattr(self,'__total'):
            self.__total = sum(item.total() for item in self.cart)
        return self.__total
    
    def due(self):
        if self.promotion is None:
            discount = 0
        else:
            discount = self.promotion.discount(self)
        return self.total() - discount
    
    def __repr__(self):
        fmt = '<Order total: {:.2f} due: {:.2f}>'
        return fmt.format(self.total(), self.due())

In [6]:
class Promotion(ABC): # the Strategy: an abstract base class
    
    @abstractmethod
    def discount(self, order):
        """Return discount as a positive dollar ammount"""

In [9]:
class FidelityPromo(Promotion): # first Concrete Strategy
    """5% discount for customers with 1000 or more fidelity points"""
    
    def discount(self, order):
        return order.total() * .05 if order.customer.fidelity >= 1000 else 0

In [53]:
class BulkItemPromo(Promotion): # second Concrete Strategy
    """10% discount for each LineItem with 20 or more units"""
    
    def discount(self, order):
        discount = 0
        for item in order.cart:
            if item.quantity >= 20:
                discount += item.total() * .1
        return discount

In [11]:
class LargeOrderPromo(Promotion): # third Concrete Strategy
    """7% discount for oders with 10 or more distinct items"""
    
    def discount(self, order):
        distinct_items = {item.product for item in order.cart}
        if len(distinct_items) >= 10:
            return order.total() * .07
        return 0

In [14]:
joe = Customer('John Doe', 0)
ann = Customer('Ann Smith', 1100)
cart = [LineItem('banana', 4, .5),
       LineItem('apple', 10, 1.5),
       LineItem('watermellon', 5, 5.0)]

In [19]:
Order(joe, cart, FidelityPromo())


Out[19]:
<Order total: 42.00 due: 42.00>

In [20]:
Order(ann, cart, FidelityPromo())


Out[20]:
<Order total: 42.00 due: 39.90>

In [27]:
banana_cart = [LineItem(' banana', 30, .5), LineItem(' apple', 10, 1.5)]

In [52]:
Order(joe, banana_cart, BulkItemPromo())


Out[52]:
<Order total: 30.00 due: 28.50>

In [32]:
long_order = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]

In [35]:
Order(joe, long_order, LargeOrderPromo())


Out[35]:
<Order total: 10.00 due: 9.30>

In [36]:
Order(joe, cart, LargeOrderPromo())


Out[36]:
<Order total: 42.00 due: 42.00>

Function-Oriented Strategy


In [54]:
from collections import namedtuple

In [57]:
class Order: # The Context
    
    def __init__(self, customer, cart, promotion=None):
        self.customer = customer
        self.cart = list(cart)
        self.promotion = promotion
        
    def total(self):
        if not hasattr(self,'__total'):
            self.__total = sum(item.total() for item in self.cart)
        return self.__total
    
    def due(self):
        if self.promotion is None:
            discount = 0
        else:
            discount = self.promotion(self)
        return self.total() - discount
    
    def __repr__(self):
        fmt = '<Order total: {:.2f} due: {:.2f}>'
        return fmt.format(self.total(), self.due())

In [58]:
def FidelityPromo(order):
    """5% discount for customers with 1000 or more fidelity points"""
    
    return order.total() * .05 if order.customer.fidelity >= 1000 else 0

In [59]:
def BulkItemPromo(order):
    """10% discount for each LineItem with 20 or more units"""
    
    discount = 0
    for item in order.cart:
        if item.quantity >= 20:
            discount += item.total() * .1
    return discount

In [61]:
def LargeOrderPromo(order):
    """7% discount for oders with 10 or more distinct items"""
    
    distinct_items = {item.product for item in order.cart}
    if len(distinct_items) >= 10:
        return order.total() * .07
    return 0

In [64]:
Order(joe, cart, FidelityPromo)


Out[64]:
<Order total: 42.00 due: 42.00>

In [66]:
Order(ann, cart, FidelityPromo)


Out[66]:
<Order total: 42.00 due: 39.90>

In [67]:
Order(joe, banana_cart, BulkItemPromo)


Out[67]:
<Order total: 30.00 due: 28.50>

In [68]:
Order(joe, long_order, LargeOrderPromo)


Out[68]:
<Order total: 10.00 due: 9.30>

In [69]:
Order(joe, cart, LargeOrderPromo)


Out[69]:
<Order total: 42.00 due: 42.00>

Choosing the Best Strategy: Simple Approach


In [ ]: