Monday, July 30, 2007

Life without Overloads

Commonly asked question at any job interview:

"What is method/function overloading?"

Method overloading is indeed one of the most commonly used and easy to get concept of languages like C\C++, Java and C#. But there are some very good programming languages, that don’t support method overloading. For a person like me who is trained only in C like languages this sounds absurd. How can a language be very good and NOT support method overloading. But as I am learning more about Ruby, my beliefs are fast changing.

Overloading is very useful when done for constructors of a class. In languages like Ruby there is no constructor as such. The 'initialize' method acts as constructor. All startup code goes into initalize method. Since method overloading is not allowed it is not possible to have overloaded constructors.

One soultion is, using array as parameter with '*' operator. This operator allows grouping all the parameters into an array. I personally find this solution inelegant, but it will work if number of desired overloads was small.

class Myclass
def initialize ( *args)
if args.size==1 then puts "function called"
end

if args.size==2 then puts "first overload called"
end

if args.size==3 then puts "second overload called"
end
end
end

a = Myclass.new(10)
b= Myclass.new(10,"abc")
c= Myclass.new("a",1,"b")

Output:
function called
first overload called
second overload called
In languages like Ruby, function parameters are 'typeless'. So instead of passing multiple parameters we could just pass a single object that contains required values. A hash (or associative array) is a good candidate for this work.
class Widget
def initialize ( *args)
@border = args[0]["border"]? args[0]["border"].to_s : "undefined"
@color = args[0]["color"]? args[0]["color"].to_s : "undefined"
@font = args[0]["font"]? args[0]["font"].to_s : "undefined"

puts "Border:#{@border}px"
puts "Color:#{@color}"
puts "Font:#{@font}\n\n"
end
end

h = {"border" => 5,"font" => "Times","color" => "RED"}
button = Widget.new(h)

Output:
Border:5px
Color:RED
Font:Times
Better still, we can use the following syntax:
button = Widget.new("border" => 5,"font" => "Times","color" => "RED")
Above syntax gives a clearer picture of how many and which values were passed. Javascript like Ruby, doesn’t allow method overloads. Similar solution works.
c1 = new dojo.dnd.Source("c1", {creator: node_creator,accept:
["red","blue"],horizontal: true});
Instead of passing an array, a JSON object can be passed. Below is code snipped using Dojo toolkit API.

The second parameter is a JSON object, which can be used to pass any number of values.Similar thing can be done in normal programming languages too !

So I am thinking.. is life impossible without overloading? ...

No comments: