Almost daily, I read forum and mailing list posts asking how to do some common Java thing in Ruby. A couple people offer solutions, and then finally a good Ruby programmer steps in and says "You can do that, but there's a totally different approach that will work much better." A staggeringly large portion of the time, the OP wants to continue down the crappy Java-like path. Why? I have no clue. The two that I see most often (and most recently) are method overloading and abstract classes.

  1. Interfaces and abstract classes are tools to get around the inflexibility of static typing
  2. Method overloading is bad OOP

Daniel Berger made a post to the Ruby list asking about how to implement a factory method. I'm not picking on him here at all, I'm only mentioning it because I provided a cool solution to his question.

Given this class Foo:

1
2
3
4
5
6
7
class Foo
  def self.inherited(subclass)
    (class << self; self; end).instance_eval do
      define_method(subclass.to_s.downcase) { subclass.new }
    end
  end
end

creating a couple subclasses will automatically create factory methods on the base class:

1
2
3
4
class Bar < Foo; end
class Zap < Foo; end
Foo.bar               => #<Bar:0x36443c>
Foo.zap               => #<Zap:0x361a34>

So why am I making this post? First of all, I wanna show off my Ruby chops :) More importantly, I hope to point out that if you're trying to write Java code in Ruby, you won't be able to come up with that solution. Ruby has a different way of doing things. Embrace it, don't fight it.

blog comments powered by Disqus