Visual BASIC 9.x 與 duck typing
Visual BASIC 與 Delphi 是少數我在 Win32 喜歡的開發環境,小時候曾經用這兩套開發過中型的 GIS (地理資訊系統),不過主要的程式碼還是用 Delphi 寫的,VB 充其量是拿來拉 UI 與作簡單的測試工具,那樣的記憶一直停留在腦海 (從上個世紀到本世紀),直到閱讀這篇由一位 MVP 撰寫的 blog [
VB的日益動態化],徹底改變我對 Visual BASIC 的看法。
VB 9 引入 Dynamic Interface 與 Dynamic Identifiers 的概念,這部份的介紹可參考 MSDN [
Overview of Visual Basic 9.0] 中 [
Dynamic Interfaces (or Strong "Duck Typing")] 與 [
Dynamic Identifiers] 兩個子項目。當然,這些技術都不算新了,早在 Smalltalk 的時代,就有完整的實做,那為何 Dynamic interface 又稱為 Strong "Duck Typing" 呢?首先來看 Wikipedia 對於 [
Duck Typing] 的解釋:
In computer science, duck typing is a term for the dynamic type system typical of some programming languages, such as with Smalltalk, where the variable value itself determines what it can do. It also implies that as long as an object implements a certain interface, it is interchangeable with any other object that implements the same interface, no matter whether the two have a related inheritance hierarchy.
The name combines two metaphors, both to make a serious point, and to make a joke. Initially used in the context of dynamic typing by Dave Thomas in the Ruby community, its premise is that if it walks like a duck, and talks like a duck, then it might as well be a duck. One can also say that the language ducks the issue of typing.
電腦科學就是這麼有趣,總是用些生動的比喻來描述這些概念。Ruby community 的 Dave Thomas 將動態語言中,物件特徵的描述用以下的話語作比喻:
if it walks like a duck, and talks like a duck, then it might as well be a duck.
這裡的 it 當然是表示 object,如果走起路來像鴨子,叫起來也像是鴨子,那麼一定是隻鴨子,saucer 的 blog [
VB的日益動態化] 舉了很好的例子,這裡就不贅述了。而 Dave Thomas 的比喻,讓我不直覺想起 Edgar Allan Poe 在《創作哲學》的詩句:
照在牠身上的燈光把牠的陰影投射在地板;
而我的靈魂,會從那團在地板上漂浮的陰暗
被擢升嗎 -- 永不復返!
這是對烏鴉的象徵,不過拿來作 duck - Object 的描述,似乎也是不錯的輔助資訊。物件導向總有高度的抽象意味,true polymorphism 的實踐,萬物 (object) 在可見度褪化為虛幻的陰影,一旦具體的形貌被抹除,Object 得以自由的變化,詩人的靈魂與鴨子的生命,在某種觀點來說,是一致的,卻又在不同軀殼有了獨特的行為...
由 jserv 發表於 January 29, 2006 05:34 PM