2015-11-05 50 views
2

变量的设计模式是长期稳定的,但会随时间变化?假设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时,向后兼容性将在过去几年中打破。我认为将这些变量放到数据库中可能是一个好主意,允许在管理面板中以某种方式对其进行修改,但必须有一些行业标准或好的做法来做到这一点。

回答

2

如果速率随时间变化,则必须使用时间相关函数进行建模。

这个功能如何确定给定的时间点或时间范围右边的数值是下一个步骤:

  1. 如果你硬编码值到程序,你必须每次更改后更改程序。
  2. 如果将其放入数据库中,则会有一个额外的数据库查询,但可以在“实施”中对其进行更改。
  3. 您还可以 - 在广泛的程序中 - 让程序从中央服务器加载正确的值并将其存储在某个地方。

根据您所使用的解决方案,你可以做

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) 
+0

您能详细介绍一下代码示例(2,3)吗? – Dominik

+0

@Dominik我添加了一些代码示例。 – glglgl

0

如果您不想在更改INCOME_TAX变量后重新计算所有以前的行,那么我建议您向表中添加一个额外列,其值为tax,因此您知道每个条目的税额是多少。

1

如果速率的变化,我想将它添加到一个中间步骤或在数据库中。这不是一个真正的常数,所以你不应该把它当作一个对待。

相关问题