This was an interview question, I was supposed to refactor the EventPricingUpdate
class to reduce the amount of nested ifs.
Here are the basic rules:
- EventPricingUpdate() is responsible for updating the price of a list of events after each day.
- Each event's price will be reduced by 10 for each day.
- The price of each event must be in the range of 50 <= price <= 500.
- The field
days_from_start
represents how many days before the event begins. Ifdays_from_start < 7
, then the effect of pricing change will be doubled. For example, a regular event's price will be reduced by 10 * 2 each day in the last 6 days. There are special event_types that behavors differently.
- "music" events' price will always go up by 10 each day, and up by 10 * 2 each day in the last 6 days.
- "construction" events' price will never change.
- "sports" events' price will drop by double the regular amount(20 instead of 10).
- The class should support easily adding new conditions for a new event_type.
As you can see below, I had trouble refactoring the nested ifs in the update() method, what are some good approach to refactor it?
class Event(object):
def __init__(self, price, days_from_start, event_type):
self.price = price
self.days_from_start = days_from_start
self.event_type = event_type
class EventPricingUpdate(object):
def __init__(self, events):
self.events = events
def update(self):
for event in self.events:
if event.event_type == 'construction':
continue
elif event.event_type == 'music':
if event.days_from_start < 7 and event.price <= 480:
event.price += 20
elif event.price <= 490:
event.price += 10
elif event.event_type == 'sports':
if event.days_from_start < 7 and event.price >= 90:
event.price -= 40
elif event.price >= 70:
event.price -= 20
elif event.days_from_start < 7 and event.price >= 70:
event.price -= 20
elif event.price >= 60:
event.price -= 10
event.days_from_start -= 1
return self.events
event_type
is sports (for eg.), according to the code above,event.price
won't ever drop below 50? \$\endgroup\$