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 [79]:
def fidelity_promo(order):
    """5% discount for customers with 1000 or more fidelity points"""
    
    return order.total() * .05 if order.customer.fidelity >= 1000 else 0

In [80]:
def bulk_item_promo(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 [81]:
def large_order_promo(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 [82]:
Order(joe, cart, FidelityPromo)


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

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


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

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


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

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


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

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


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

Choosing the Best Strategy: Simple Approach


In [87]:
promos = [fidelity_promo, bulk_item_promo, large_order_promo]

In [88]:
def best_promo(order):
    """Select best discount available"""
    
    return max(promo(order) for promo in promos)

In [89]:
Order(joe, long_order, best_promo)


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

In [90]:
Order(joe, banana_cart, best_promo)


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

In [91]:
Order(ann, cart, best_promo)


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

Finding Strategies in a Module


In [92]:
promos = [globals()[name] for name in globals()
         if name.endswith('_promo')
         and name != 'best_promo']

In [94]:
def best_promo(order):
    """Select best discount available"""
    return max(promo(order) for promo in promos)

In [96]:
import inspect

In [98]:
promos = [func for name, func in
          inspect.getmembers(promotions, inspect.isfunction)]


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-98-69ab9e407cb0> in <module>()
      1 promos = [func for name, func in
----> 2           inspect.getmembers(promotions, inspect.isfunction)]

NameError: name 'promotions' is not defined

Command


In [99]:
class MacroCommand:
    """A command that executes a list of commands"""
    
    def __init__(self, commands):
        self.commands = list(commands)
        
    def __call__(self):
        for command in self.commands:
            command()

In [ ]: