l

2015年1月19日 星期一

更精確的壞味道定義(上)

Jan. 18 17:24~18:20

螢幕截圖 2015-01-18 22.32.16

 

最近重新著手繼續準備荒廢了一陣子的 Refactoring 教材(今年一定會開課,否則C. C. Agile活動請吃大家雞排XD),為了設計教材前兩天在家裡讀了三篇學術論文。不就是 refactoring 嗎,這可是「實戰」課程,為什麼做教材要讀論文?因為Teddy覺得自己的層次累積的還不夠深,心中還有一些問號沒被打破(地鼠還沒打完)。

這幾集部落個將介紹〈Improving the Precision of Fowler’s Definitions of Bad Smells〉這篇論文,該論文幫Fowler 書中的Data ClumpsMessage ChainsMiddle ManSpeculative GeneralitySwitch Statements這五個壞味道提供了pattern-based definition,希望藉由這些定義讓開發人員或試自動化工具可以比較容易找出程式中的壞味道。

***

Data Clumps(資料泥團)

先看一下Fowler書中對於Data Clumps壞味道的原始定義:

Data items hang around in groups. Often you will see the same three or four data items together in lots of places: fields in a couple of classes, parameters in many method signatures.

這篇論文把Data Clumps壞味道改用下列兩種狀況來表示(直接引用論文的內容):

  • 狀況1
    1. More than three data fields stay together in more than on class.
    2. These data fields should have same signatures (same names, same data types, and same access modifiers).
    3. There data fields may not group together in the same order.
  • 狀況2
    1. More than three input parameters stay together in more than one methods’ declaration.
    2. These parameters should have same signatures (same names, same data types).
    3. These parameters may not group together in the same orders.
    4. The methods should not in a same inheritance hierarchy and with a same method signature.

和Fowler的定義相比,其實大同小異,不過論文的講法明確指出Data Clumps就只有這兩種情況,而且資料出現的順序可以不一樣,但是signatures必須相同。最後還有一個重點,就是狀況2的第4點,如果是overloading methods的參數就不屬於Data Clumps。語意上論文中的講法是比較清楚一些,Fowler的講法比較精簡。

關於Data Clumps壞味道,可以參考〈談談壞味道(5):Data Clumps & Primitive Obsession〉。

***

Message Chains(訊息鏈)

先看一下Fowler書中對於Message Chains壞味道的原始定義:

You see message chains when a client asks one object for another object, which the client then asks for yet another object, which the client then ask for yet another another object, and so on. You may see these as a long line of getThis methods, or as a sequence of temps.

這篇論文把Message Chains壞味道以下列兩種狀況來表示(直接引用論文的內容):

  • 狀況1
    1. In order to access a data field in another class, a statement needs to call more than a threshold value of getter methods in a sequence. (e.g., int a=b.getC().getD();)
    2. This method call statement and the declarations of getter methods are in different classes.
  • 狀況2
    1. A method has more than a threshold number of temp variable.
    2. A temp variable is that a variable only access data members () of the other classes or other temp variables.

論文中對於Message Chains壞味道的敘述和Fowler的定義相比差異不大,只不過將需要呼叫幾層的method以一個threshold來表示,增加規則的彈性。

關於Message Chains壞味道,可以參考〈談談壞味道(8):Temporary Field & Message Chains〉。

***

友藏內心獨白:有沒有更精確,讓我們繼續看下去。

1 則留言:

  1. 文中Data Clumps狀況1第1點的最後面,是否應該是"one" class而不是"on" class?

    回覆刪除