views:

170

answers:

2

Apologies for the recursive nature of this question but the chosen answer to a question on SO got me questioning my understanding of reflection.

I thought reflection was mainly about querying the internal happenings of a program while it's running. The example given in this response patches Ruby's built-in Integer class.

  • Isn't this more like function overloading/inheritance rather than runtime modification?
  • Is class reopening really an example of reflection?
+2  A: 

Reflection can be used to implement late binding.

Late binding can be used to implement monkey patching.

Monkey patching can be used to achieve the sort of coding style shown in that answer.

But there are other ways to implement such features that don't require monkey patching, or reflection. Heck, a good macro pre-compiler could get you close.

So, technically correct, but not (IMHO) the greatest example.

Shog9
IYO, what would be a more effective example of reflection?
notnot
+1  A: 

At the risk of increasing the level of recursion, I would like to respond although you are referencing my answer at that link.

The misunderstanding is an easy one to make because of our intuitive understanding of reflection as referring to looking inwards. And that's certainly an important aspect of reflection in programming also - in Ruby, for example, we have methods like instance_of to allow objects to ask questions about themselves at runtime.

But take a look at the wikipedia definition of reflection:

reflection is the process by which a computer program can observe and modify its own structure and behaviour.

As you can see, reflection is more than just runtime self-inspection. It's also the ability to change runtime behavior. Reopening a class is also referred to as "monkey patching". You can read more about it here.

A monkey patch is a way to extend or modify the runtime code of dynamic languages without altering the original source code.

This process is also referred to as: - Guerrilla patching - Extending previously declared classes - Reopening classes - Dynamic Funk - Hijacking - Duck Punching - Method Swizzling

Serx