If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?

前端 未结 8 1395
一向
一向 2021-02-05 12:34

In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary c

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 12:45

    The languages might permit it, but neither community condones the practice. Monkeypatching isn't condoned in either language, but you hear about it more often in Ruby because the form of open class it uses makes it very, very easy to monkeypatch a class and because of this, it's more acceptable in the Ruby community, but still frowned upon. Monkeypatching simply isn't as prevalent or as easy in Python, which is why you won't hear the same arguments against it in that community. Python does nothing that Ruby doesn't do to prevent the practice.

    The reason you hear/read about it more often in Ruby is that this in Ruby:

    class MyClass
      def foo
        puts "foo"
      end
    end
    
    class MyClass
      def bar
        puts "bar"
      end
    end
    

    will give you a class that contains two methods, foo and bar, whereas this in Python:

    class MyClass:
        def foo(self):
            print "foo"
    
    class MyClass:
        def bar(self):
            print "bar"
    

    will leave you with a class that only contains the method bar, as redefinition of a class clobbers the previous definition completely. To monkeypatch in Python, you actually have to write this:

    class MyClass:
        def foo(self):
            print "foo"
    
    def bar(self):
        print "bar"
    MyClass.bar = bar
    

    which is harder than the Ruby version. That alone makes Ruby code much easier to monkeypatch than Python code.

提交回复
热议问题