Friday, March 16, 2012

Matz answers why Ruby lets sub classes to access private methods in super class

In Ruby, private methods in super class can be called from sub class. If you are a Java or C# programmer, you would be surprised at such behavior like me.

class Foo
  protected
  def protected_method_in_foo
    "Hello."
  end

  private
  def private_method_in_foo
    "Bye."
  end
end

class Bar < Foo
  def say_hello
    protected_method_in_foo
  end

  def say_bye
    private_method_in_foo # OK
  end
end

bar = Bar.new
puts bar.say_hello # Hello.
puts bar.say_bye # Bye.

The difference between private methods and protected methods is a little difficult too. Protected methods can be called from the instances of sub classes via receivers, but private methods cannot do the same.

class Foo
  protected
  def protected_method_in_foo
    "Hello."
  end

  private
  def private_method_in_foo
    "Bye."
  end
end

class Bar < Foo
  def say_hello_via(foo)
    foo.protected_method_in_foo
  end

  def say_bye_via(foo)
    foo.private_method_in_foo # NG!!
  end
end

foo = Foo.new
bar = Bar.new
puts bar.say_hello_via foo # Hello.
#puts bar.say_bye_via foo # NoMethodError!!

Matz answers why

I wanted to know why Ruby is designed like this, so I asked Yukihiro "Matz" Matsumoto. He readily answered my questions. I am thankful to him.

Me: I would like to know why Ruby lets sub classes to call private methods in super class. What is the design concept? And are there any programming languages that behave like Ruby?

Matz: I did not expect that Java or C++ programmers tend to misunderstand the keyword "private". When I designed Ruby for the first time, Java had not been released. And I did not consider "private" (and other keywords) because they are C++ specific functions.

Matz: Ruby's "private" was inspired by the "private categories" in Smalltalk, which means just "Please do not use", but they are accessible. Ruby is a little stricter than Smalltalk. That is a part of the concept - anti-C++ and pro-Smalltalk.

Matz: The keyword "protected" was introduced later, but that was not a good idea because that had brought the same keyword and the different meaning between Ruby and C++.

Other person: If Matz introduced the function now, what keyword would he choose? I wonder.

Matz: If now? I would not introduce "protected".

Summary

The Ruby was designed prior to Java/C# and the keyword "private" was inspired by Smalltalk. That is why the behavior between Ruby and Java/C# is different.

I wrote the same article in Japanese: http://d.hatena.ne.jp/JunichiIto/20120315/1331754912

No comments:

Post a Comment