2013-03-20 60 views
5

我正在開發一個項目。目前我有一個相當大的條件語句,它根據一些輸入參數爲變量賦值。所以,我有這樣的事情。重構條件變量賦值

if some condition 
    x = some value 
elsif another condition 
    x = a different value 
    ... 

什麼是最好的重構方式?我希望我可能最終得到類似

x = some value if some condition || another value if another condition 

是否有這種事情的模式?

+0

在我們可以告訴你如何重構之前,你需要告訴我們爲什麼要重構這個。你想解決什麼問題? – 2013-03-20 22:17:05

+2

'重構=零,除非存在嗎?(:unit_tests)' – dbenhur 2013-03-21 04:59:29

回答

9

只需將賦值放在if之外即可。

x = if some condition 
    some value 
elsif another condition 
    a different value 

或者你可以使用哈希。

x = dict[some condition] 
0

它不是一個模式,而是一個操作符。你指的是一個是三元運算符:

If Condition is true ? Then value X : Otherwise value Y 

下面是一個例子:

speed = 90 
speed > 55 ? puts("I can't drive 55!") : puts("I'm a careful driver") 

使用三元說法是短暫的,甜的,做這項工作。

+0

我的條件是,如果其他人則比更長的時間。 – 2013-03-20 22:27:35

+0

然後,我會堅持'if/elsif'語句。使用這些沒有任何問題。 – BlackHatSamurai 2013-03-20 22:29:33

+0

'puts(速度> 55)? 「我不能開車55!」 :「我是一個細心的司機」' – ZiggidyCreative 2017-02-22 11:43:09

0
x = some condition ? some value : 
    another condition ? a different value : ... 
+1

嵌套?不是一個好習慣。 – 2013-10-19 17:58:18

1

條件語句也是一種表達,所以你可以做的第一件事,如果變量是在每個條件是相同的,就是:

x = if cond1 
    expr1 
elsif cond2 
    expr2 
.... 
end 

如果條件都是單一表達式的狀態,你可以使用case語句使它更整潔。

然而,下一個最明顯的重新分解練習是讓大有條件隔離成一個方法,它應喂以評估所有條件和表達所要求的最低數據。

E.g.

# Where conditional is currently, and x assigned, assuming the conditionals 
# need a couple of variables . . . 
x = foo param1, param2 

# Elsewhere 
private 

def foo p1, p2 
    if cond1 
    expr1 
    elsif cond2 
    expr2 
    .... 
    end 
end 
0

如果要重構代碼的清晰度和靈活性,考慮replacing conditional with polymorphism重構。

有沒有足夠的細節在你的問題與建議走得更遠,但這種重構會使你的代碼庫更加抗拒改變。如果您收到一個新的要求,那麼打破條件並修改它(更容易引入錯誤,更困難)是不好的形式;最好創建一個可插入現有代碼庫的新對象。這種靈活性是Open/Closed Principle(SOLID首字母縮略詞中的「O」)所描述的。