Duck Typing

Ruby 是個 dynamically-typed language,《Programming Ruby, 2/e》裡面形容所謂 "duck typing":

def append_song(result, song)
  result << song.title << " (" << song.artist << ")"

result = ""
append_song(result, song)

You don't need to check the type of the arguments. If they support << (in the case of result) or title and artist (in the case of song), everything will just work. If they don't your method will throw an exception anyway (just as it would have done if you'd checked the types). But without the check, your method is suddenly a lot more flexible: you could pass it an array, a string, a file, or any other object that appends using <<, and it would just work.

這說法太熟悉了 ─ Generic Programming!

template<typename A, typename S>
A& append_song(A& result, const S& song) {
  result << song.title() << " (" << song.artist() << ")";
  return result;

而且這是 dynamic generic programming!或者該說,static generic programming 因為能作用於一類型別上而稱「泛型」,而所謂 "dynamic generic programming" 根本不考慮型別,而事實上無所謂「泛型」。的確,先前只接觸 statically-typed C/C++ & Java,沒考慮過動態型別語言在此處的優勢 ─ generic programming 對於動態型別語言根本無意義!先前建立的 OO 思維應該也有一些必須修正。

Blogger yen37/06/2006 8:58 am 說:

generic programming 對於動態型別語言根本無意義!



<< 回到主頁