From: Curt Hibbs Date: 2004-06-09T00:27:14+09:00 Subject: Re: Expressing intent in method calling... Richard Kilmer wrote: > > This is not a continuation of the type thread other than trying > to continue > to discuss the ideas of adding metadata that could be used to help the > runtime environment of Ruby. Before anyone says anything, I have > built lots > of Ruby code without this, and the runtime is just fine...think of this as > exploration. Disregard all the other syntax I wrote on earlier...and I do > not care whether something is Hash-like, or is_a? Duck ;-) > > class Person > attr_accessor :name > end > > def greet(person) > puts "Hello there #{person.name}" > end > > So, greet was coded thinking its sending the 'name' message to a Person > object...and that is expressed with the metadata . > > o = Object.new > def o.name > if called_as?(Person) > "Rich" > else > to_s > end > end > > You build your object to accept being called as a Person, but it can be > called as anything else too...it just responds to the name method > differently if its being asked 'as a Person'. > > greet(o) => "Hello there Rich" > > What this adds is the ability to express the intent of the caller > as to what > they mean by sending the message 'name' (ie. name, as in a Person's name). > The receiver can find out the caller's intent > (called_as?(Person)). It also > lets the receiver change into what the caller wants it to be (kinda like > become...one method at a time). This is a very interesting concept and, in general, I like it. My initial reaction was why not just have a method named "person_name", but quickly realized that this is much more powerful. Objects that respond to name but do not understand can still be used (this might be considered a "degraded" use, whereas an object that can use the metadata can operate in an "enhanced" manner. While this shows the use of metadata as part of sending a message, a similar syntax could be used to attach metadata to methods and classes as is done in .NET. As with .NET, this metadata could be inspected at runtime to enable the creation of enhanced runtime facilities like Aspects and Unit Testing. For example, I particularly like the way NUnit for .NET (http://www.nunit.org/) implements unit testing, and metadata for classes and methods in Ruby could able this technique for TestUnit: class MyTests def create_clean_database ... end def create_db_entry ... end def update_db_entry ... end end An AOP example could use metadata to identify target pointcuts (perhaps at the method level): class BankAccount ... def balance? ... end end In this example, a runtime AOP framework could, for example, wrap the "balance?" method with AOP defined permission checks. I'm sure there are some synergistic possibilities between metedata on methods and classes and metadata attached to messages, but I haven't had time to think about that yet. Curt