11 ottobre 2011

eXtreme Polymorphism

from the object-oriented dept.


Idea idea! What about polymorphic conditionals? In such a way, we don't need the if, else and related keywords. Let's try in Ruby:



class FalseClass
def if_false(&block)
block.call
self
end
def if_true(&block)
self
end
end
class TrueClass
def if_true(&block)
block.call
self
end
def if_false(&block)
self
end
end
# example
(1>2).if_true{puts "yes"}.if_false{puts "no"}
view raw polymorph_if hosted with ❤ by GitHub


Great, isn't it? But wait, someone already invented this! :-)

Ruby is a great language, however it has too many keywords that could be substituted with object-level messages. Simplicity always leads to elegant solutions, and Smalltalkers know what I am talking about.