Wednesday, April 20, 2016

Duck-typing and monkey-patching

These are two different concepts / programming approaches.

Duck typing - A programming concept that is primarily concerned with the methods that can be run on an object rather than the Class of the object. Ruby allows you to pass an object to a method in another Class so long as that object can take that method. "if it quacks like a duck, then it's a duck".
(good example here: Duck Typing: Ruby Study Notes)

Monkey patching - Unlike many other languages, Ruby allows you to reopen classes, including system classes or third party library classes linked to by your program, and add new methods to them or overwrite existing methods, at run time.
For example, your code could reopen the String.to_i method and have it do something different in your particular program by simply doing:

  1. class String
  2. def to_i
  3. my custom to_i method code
  4. end
  5. end

   With great power comes the danger of misuse or abuse, and monkey patching is no exception. It can be easy to introduce bugs or can make debugging very difficult if you forget the expected behaviour is changed, especially later when someone else is maintaining the code. It's more useful for adding useful methods to a class.
   Monkey patching allows you to come up with a "quick and dirty" solution to a problem, but you should use it very sparingly. For example, if you're extending a third party library (gem), you could fork the gem instead. (see The End of Monkeypatching)