Part 18 - Duck Typing
|title||Definition: Duck Typing|
Duck typing is a humorous way of describing the type non-checking system. Initially coined by Dave Thomas in the Ruby community, its premise is that (referring to a value) "if it walks like a duck, and talks like a duck, then it is a duck".
Even though Boo is a statically typed language, Duck Typing is a way to fake being a dynamic language. Duck typing allows variables to be recognized at runtime, instead of compile time. Though this can add a sense of simplicity, it does remove a large security barrier.
|title||Duck Typing Example|
d as duck
d = 5 // currently set to an integer.
d += 10 // It can do everything an integer does.
d = "Hi there" // sets it to a string.
d = d.ToUpper() // It can do everything a string does.
Duck typing is very handy if you are loading from a factory or an unpredictable dynamic library.
Do not enable duck typing by default. It should only be used in a few situations.
On a side note, The
booish interpreter has duck typing enabled by default. This can be disabled by typing in
interpreter.Ducky = false
Here is a practical example of where duck typing is useful.
|title||Practical Duck Typing|
type = System.Type.GetTypeFromProgID(progid)
ie as duck = CreateInstance("InternetExplorer.Application")
ie.Visible = true
document = ie.Document
print("$(document.title) is $(document.fileSize) bytes long.")
- Come up with another good example where duck typing is effective.
Go on to Part 19 - Using the Boo Compiler