2015-11-05 51 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

如果速率的變化,我想將它添加到一箇中間步驟或在數據庫中。這不是一個真正的常數,所以你不應該把它當作一個對待。

相關問題