长期稳定但可以及时变化的变量的设计模式是什么?让我们假设2015年和2016年的所得税为18%,从2017年1月1日起将有20%。
INCOME_TAX = 0.18
def _calculate_tax(self, income, tax=INCOME_TAX):
return income*tax
2017年,当INCOME_TAX将更改为0.2时,向后兼容性将在前几年中被打破。我认为将这些变量放入数据库可能有一个好主意,允许在管理面板中以某种方式修改它们,但必须有一些行业标准或良好做法。
答案 0 :(得分:2)
如果费率随时间变化,则必须通过时间相关函数建模。
此功能如何确定给定时间点或时间范围的正确值是下一步:
根据您使用的解决方案,您可以
def calculate_tax_for_year(self, income, year):
return _calculate_tax_for_year(self, income, tax_for_year(year)):
def tax_for_year(year): # solution 1
if year < 2010: return .2
if year < 2013: return .18
# etc.
def tax_for_year(year): # solution 2
with dbconn as cursor:
cursor.execute("SELECT rate FROM taxrate WHERE year == %s", year)
return cursor.fetch_one_row() # don't remember the syntax; something like this...
# solution 3:
def tax_for_year(year):
# just describing the steps:
with open("path/to/taxfile", "r") as f:
taxdata = f.read()
# parse table file, e. g. CSV
# find the right entry
return entry_matching_for_given_year
def update_tax_file():
import urllib
conn = urllib.urlopen("http://my.taxfile/url.csv")
# check if the file has changed since last check
# if so:
data = conn.read()
with open("path/to/taxfile", "w") as f:
f.write(data)
答案 1 :(得分:1)
如果费率发生变化,我会将其添加到中间步骤或数据库中。这不是一个真正的常数,所以你不应该把它视为一个。
答案 2 :(得分:0)
如果您不希望在更改INCOME_TAX
变量后重新计算所有先前的行,那么我建议您在表中添加一个额外的列,其值为tax
,这样您就知道了什么是每个条目的税。