2015-07-21 57 views
0

這是處理匯款的活動記錄類。如何擺脫所有功能中的類似說法

class Wallet < ActiveRecord::Base 
    belongs_to :user 
    has_many :deposits, dependent: :destroy 
    has_many :deposit_requests, dependent: :destroy 
    has_many :withdrawals, dependent: :destroy 
    has_many :withdrawal_requests, dependent: :destroy 

    def deposit_with_tax_deduction! amount 
    deposit! amount 
    deduct_tax(amount) 
    end 

    def deposit! amount 
    deposits.create! amount: amount - tax_for(amount) 
    end 

    def withdraw! amount 
    if can_spend? amount 
     withdrawals.create! amount: amount 
    else 
     raise "Недостаточно средств" 
    end 
    end 

    def total 
    deposits.sum(:amount) - withdrawals.sum(:amount) + deposit_requests.success.sum(:amount) - withdrawal_requests.success.sum(:amount) 
    end 

    def can_spend? amount 
    total - amount > 0 
    end 

    def tax_for(amount) 
    amount.to_f * Option.current.tax/100 
    end 

    private 
    def deduct_tax(amount) 
    AdminWallet.deposit! amount 
    end 
end 

我幾乎在課堂上的每種方法都有相同的論點(amount)。它是一種代碼味道,可能會導致多年後的不良後果?我應該遵循什麼模式?

回答

2

這是好的。

實例變量通常被認爲是對象的狀態。在你的情況下,「量」變量將是狀態的不必要的變化,因爲除了當前執行之外它沒有任何重要性。

但是,對我來說提及這裏沒有嚴格的規則是很重要的。這很大程度上取決於班級的性質。通常我們區分數據對象行爲對象。前者通常更持久,而後者在使用上更具可配置性。因此,「國家」這個詞在每個詞中都有不同的含義。

目前,作爲「錢包」類顧名思義,你有一個數據對象。稍後,您可能會重構您的代碼並創建一個「Transaction」類。在這種類中,設置量作爲實例變量更有意義。您甚至可以輕鬆地使用Command模式來撤銷您的操作。

順便說一句,傳遞的參數誇張的量是一個代碼的氣味,這意味着,你應該考慮拆分您的代碼轉換成更多的類。請記住:不要試圖去解決你可能在幾年的問題。專注於你現在遇到的問題。

0

您可以定義金額爲instance variable,因爲你的方法也instance methods

所以

class Wallet < ActiveRecord::Base 
    ... 
    attr_accessor :amount 

    def tax_for 
    end 
    ... 
end 

,您可以通過(前)用它

wallet = Wallet.new 
wallet.amount = 100 
wallet.tax_for