Safe monkey patching in Scala

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com

I get how clever and interesting this is.:

The biggest drawback from doing this in Ruby is monkey patches are in the global scope. If you use any class that relies on any monkey patching then that monkey patching is also in your scope. At best it won’t effect any of your code, at worst it can silently override methods in your code. This can lead to horrible problems that will cause you to cry.

Scala however lets you accomplish the same thing without polluting the global scope. It achieves this by the use of implicits, a mechanism to instruct the compiler to transparently convert one type to another at compile time.

There was also Michele Simionato’s argument Mixins considered harmful (Python examples):

For instance, have a look at the hierarchy of the Plone Site class which I report in appendix. Between square backets you can see the number of methods/attributes defined per class, except special attributes. The plot comes from a real Plone application I have in production. The total count is of 38 classes, 88 names overridden, 42 special names and 648 regular names: a monster.

To trace the origin of the methods and to keep in mind the hierarchy is practically impossibile. Moreover, both autocompletion and the builtin help facility become unusable, the self-generated class documentation become unreadable since too big.

In other words, a design based on mixins works for small frameworks, but it does not scale at all to large frameworks. Actually, Zope 3 has been entirely rewritten with the goal of avoiding the mixin abuse of Zope 2 and to use composition instead of inheritance (this is basically what the buzzwords Component Architecture really mean).

In both cases, Lisp style macros would offer more functionality for less complexity. So why not simply use a Lisp like Clojure?

In the above article the goal is stated as:

This allows us to build Ruby like DSLs without the fuss of global monkey patching.

If that is the goal, then, again, the question should be, why not use a Lisp? Lisp allows for macros that allow you to completely change your language. There is the old saying “Lisp is the language in which you write the language that you will use to solve your problem.”

I get that the people behind Scala are very intelligent, but I wonder if that intelligence is not being wasted on something that is a bit too clever?

Source