3 ms·
To me, a big advantage of Scala's "enrichment" over monkey-patching in Ruby or JS is that it isn't global. That is, you have to import the enrichment. Another c
by hp 15y ago
To me, a big advantage of Scala's "enrichment" over monkey-patching in Ruby or JS is that it isn't global. That is, you have to import the enrichment. Another code module in the program won't be unexpectedly affected by it.
In practice, I almost never use monkey-patching in dynamic languages because it's too dangerous. While in Scala there are cases where enrichment won't work, you can always just write a regular function in those cases, and there are lots of cases where enrichment _does_ work...
- rue 15y agoAdding and/or altering functionality at runtime isn't dangerous. Monkeypatching may be, so avoid that. Also, an entirely too-little used idiom (blame Rails programmers): module OverrideSomeMethod def some_method … end end s = SomeClass.new s.extend OverrideSomeMethod s.some_method
- draegtun 15y agoThis is an idiom I use regularly (in Perl, Ruby, Io & Javascript) and come across it often in the Perl world where Moose roles are used. The only downside of this idiom is the extra runtime cost which maybe an issue for Rails?
- draegtun 15y agoSome languages make monkeypatching a lot less dangerous. For eg. in Perl you can use dynamic scoping to localise its effect: { no warnings 'redefine'; local *SomeModule::some_func = sub { say "MONKEYPATCHED!" }; # now everything in this scope that uses or calls SomeModule->some_func # will now use the monkeypatched version } # where has everything else outside this scope remains unaffected In Ruby Refinements earmarked for ruby 2.0 will have something similar: http://www.rubyinside.com/ruby-refinements-an-overview-of-a-new-proposed-ruby-feature-3978.html http://www.rubyinside.com/ruby-refinements-an-overview-of-a-...