Home > Uncategorized > Runtime alteration of an object or type system

Runtime alteration of an object or type system

Note: A lot of this stuff is CTRL+C, CTLR+V. I have just tried to consolidate stuff into one single article. I can come back to this one article & coherently read this from one single article, instead of jumping over a dozens of pages and get lost. So I do not claim credits for any of the stuff here.

A type or object system can typically be modified during runtime in a dynamic language. This can mean generating new objects from a runtime definition or based on mixins of existing types or objects. This can also refer to changing the inheritance or type tree, and thus altering the way that existing types behave (especially with respect to the invocation of methods) [1].

Let us start with another example from the Pick-axe book.

Executing the following code
    num=81
    6.timesdo
        puts "#{num.class}: #{num}"
        num *= num
    end

produces:
Fixnum:81
Fixnum:6561
Fixnum:43046721
Bignum:1853020188851841
Bignum:3433683820292512484657849089281
Bignum:11790184577738583171520872861412518665678211592275841109096961

Yes the object’s type changes during the program’s execution life-time. Next, Let us see something about mixins:

A mixin is like an interface along with its implementation, which can be attached to any class. It is like controlled multiple inheritance. It is like a ‘run-time’ aware partial class which can be mixed in with any client class. Let us see an example and description from the ‘Pick-Axe’ again:

module Debug
       def who_am_i?
               "#{self.class.name}  (##{self.id}): #{self.to_s}"
       end
end
class Phonograph
        include Debug
        #…
end
class EightTrack
        include Debug
        #…
end

ph = Phonograph.new("WestEndBlues")
et = EightTrack.new("SurrealisticPillow")

ph.who_am_i?  –> "Phonograph (#935520): WestEndBlues"
et.who_am_i?  –> "EightTrack (#935500): SurrealisticPillow"

The Debug Mixin gets mixed in with the classes EightTrack and PhonoGraph client classes (called mixees). Loggers, Enumerators, Comparers, Cloning and a lot of other useful features which we need across all (unrelated set of) objects can be implemented and mixins and mixed in into any client class.

Some object-oriented languages(such as C++) support multiple inheritance, where a class can have more than one immediate parent,inheriting functionality from each. Although powerful,this technique can be dangerous, as the inheritance hierarchy can become ambiguous.

Otherlanguages,such as Java and C#,support single inheritance. Here,a class can have only one immediate parent. Although cleaner (and easier to implement), single inheritance also has drawbacks in the real-world objects often inherit attributes from multiple sources(a ball is both a bouncing thing and a spherical thing, for example).

Mixins offer an interesting and powerful compromise,giving you the simplicity of single inheritance and the power of multiple inheritance. A Ruby class has only one direct parent, so Ruby is a single-inheritance language. However, Ruby classes can include the functionality of any number of mixins (a mixin is like a partial class definition). This provides a controlled multiple-inheritance-like capability with none of the drawbacks.

Method Interception: [3]
In Ruby, to do method interception, you simply rename and replace a method, with the new implementation calling the old
Here’s one example from the standard library. Date objects are immutable, so once you calculate the day of the week for any given date object, you could store that result and return it in later invocations without redoing the entire calculation. The code to check for a previously calculated value is simple enough to write, but it is tedious to implement it in each of the 13 or so methods in Date that could take advantage of it.

The author of the Date class took this approach. He wrote each method as if it would recalculate the value every time it was called (i.e., no special checking for previous values). Then he wrote a class method called once that takes a list of method names. The once method did the following: created an alias for the named method; made that alias private; and created a new method with the original name that checked for a previously calculated value before calling the original code (via the alias). In other words, the once method rewrote existing methods to calculate its return value once and store the result.

def meth
    "original method"
end
alias original meth
def meth
    "new and improved"
end
meth –> "new and improved"
original –> "original method"

How much ruby makes it easier to follow the Once and Only Once principle…

Method Missing [2]
Invoked by ruby when an object is sent a message and the object cannot handle the message.
class Roman
    def roman_to_int(str)
        #…
     end
    def method_missing(method_id)
        str=method_id.id2name
        roman_to_int(str)
    end
end
r=Roman.new
r.iv –> 4
r.xxiii –> 23
r.mm –> 2000

This is kind of cool when you want a natural language feel. You will love these if you are into DSLs. "A more typical use of method_missing is to implement proxies, delegators,and forwarders." [2]

"The important thing to remember about Ruby is that there isn’t a big difference between “compiletime” and “runtime.” It’s all the same. You can add code to a running process. You can redefine methods on the fly, change their scope from public to private, and so on.You can even alter basic types, such as Class and object. Once you get used to this flexibility, it is hard to go back to a static language such as C++ or even to a half-static language such as Java. But then, why would you want to do that?" [2]

[1] Dynamic Programming Language – http://en.wikipedia.org/wiki/Dynamic_language
[2] Programming Ruby: The Pragmatic Programmer’s guide – http://www.pragprog.com/titles/ruby
[3] Ruby in the rough – http://www.brainbell.com/tutorials/java/Applying_Some_Structure.htm

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: