Iris Classon
Iris Classon - In Love with Code

‘Stupid’ Question 5: What is reflection (in Net) ?

At the gym I use reflection to check my technique so I can adjust it while I am doing the exercise ( during ‘runtime’)

[To celebrate my first year of programming I will ask a ‘stupid’ questions daily on my blog for a year, to make sure I learn at least 365 new things during my second year as a developer]

During my first year I heard a lot about this thing called ‘reflection’. I also heard various definitions, but I actually never really understood what it was. As with many questions, I forgot about it and it remained on my ‘I should find out this’-list, as I got the impression that it was something complicated that should be left for later.
Untill a few days ago. I was working on navigation on my Metro app, I got to think about reflection as I was wondering how GetType() and TypeOf() was working- I know what they DO but not HOW. And I suddenly realized what reflection is, and that I have been using it all along, as a programmer as well as for example at the gym.

Reflection lets you get information about a type or assembly at runtime in your code. It’s like when I do weighttraining at the gym, I need to check my techinque while I am doing the exercise, as I don’t know beforehand what to correct. So I will use the mirrors and ‘fetch information’ throughthe reflection, and then dynamically use that information so the exercise is correctly done.

I’ve found these two discussions on StackOverflow quite helpfull,
1.What exactly is Reflection and when is it a good approach?
2.When do you use reflection? Patterns/anti-patterns
-and they have also made me reconsider my usage of reflection and made me further look up “How slow is reflection”? I don’t have the answer for that yet, do you know? Please share!

Comments

Leave a comment below, or by email.
Esko Luontola
7/22/2012 5:08:03 PM
Though reflection is slower than non-reflection, we are only talking about times in the nanosecond range. For example it calling a method normally takes 1 ns, with reflection it might take 3-5 ns. As always with performance: profile and find your bottleneck before optimizing. Keep the code clean and it will be easy to optimize later where it matters.

Reflection is good for handling situations which would otherwise be impossible to implement, or would require lots of boilerplate code. There are ways to do things faster than reflection (for example code generation at runtime or compile time), but those are much harder to use than reflection. (Based on my recent experiences, using bytecode manipulation or source code generation requires in the order of 10 times more work than using reflection.)

Some years ago I was practicing reflection (and TDD) by writing an application which can take as input a string "foo abc 123" and then using reflection does the method call foo("abc", 123) on an object. In nearly every project I've had some use for reflection, so it's good to keep at hand in your toolbox. 
tsells
7/23/2012 5:26:25 PM
Here is a good use of reflection along with some performance numbers.


http://tsells.wordpress.com/2011/02/08/using-reflection-with-wpf-and-the-inotifypropertychanged-interface/ 
James Curran
7/24/2012 7:43:38 AM
I've long felt the Reflection get a bad name due to it's frequent misuse.  There's is nothing inherently slow about reflection; the problem is that it is often used for things that could be done much faster using inheritance/polymorphism or method overloading. 
Daniel COHEN-ZARDI
7/24/2012 2:51:29 PM
Though powerful when used properly, reflection is often over-used.

The main issue is not performance, it is the fact that using a "dynamic" approach might make your software less robust and harder to maintain.

Once you get an error in production, it is much more complex to support and debug than a static approach.

In my view, to some extent, it is a little bit like using languages that have no types (or interpreted languages versus compiled languages). It is very powerful and flexible but has drawbacks when overly used. 
Daniel COHEN-ZARDI
7/24/2012 2:52:23 PM
Correcting my previous comment : one needs to read "less robust" 
SondreB
7/27/2012 12:57:22 AM
As others have mentioned, reflection does not come with a very hard performance penalty, at least not these days. It depends on what you are doing.

The question is the trade off you need to do: Should you use reflection to save time, write less code and have less bugs - or write more code, possibly more bugs? :-) 
Chad Carter
7/29/2012 8:03:17 PM
A real world example where I've used reflection is when I need to allow for modules to be plugged in later.

For example in an ecommerce application I architected I added a table called catalog_logic_assemblies.  This table contained all of the information needed to create an instance of the assembly at runtime.  95% of the time the assembly to be used will always be a particular assembly.

So I have an assembly for Credit Card logic.  It always talks to the primary payment gateway.  But we have had occasion where we needed to integrate with another gateway.  So we simply create a new catalog logic assembly for credit cards and if a record is present, we instantiate the assembly declared in the database instead of the default one.

So 95% of the time there is no credit card record present in that table.  When no record is present, we just call the default assembly normally.  But when it is present, we create it through reflection.

This approach was chosen because we have the same core code base running hundreds of ecommerce sites for our clients.  While most will use the standard assemblies, there are times when we need to invoke different logic based on the need of the client or project.  Times like these, it makes maintaining the code much more simple since everything still shares the same codebase and just the records in the database dictate which assembly is actually instantiated.

For web applications, there has been no measurable slowness when reflection is used.  The time the code takes to execute isn't a bottleneck, it is database calls and overall bandwidth. 
Justin
10/16/2012 6:34:56 PM
I used reflection for a simple factory pattern in a custom ERP that I built at my last job. I think it is a good use case for reflection. I had to build a module for the tax department. The "fun" thing about taxes is that every state has different ways of doing things, which meant the system had to do different things based on the state chosen by the user. There was a drop-down with the states that we dealt with that the user would use to choose. Then when the user clicked a button, the code would call a factory class and pass in the name of the state. I built an abstract class for all of the states' classes to inherit from so that each can process the items according to the state's policies. The names of the classes were the same as the state names that were chosen by the user. So the factory would use reflection to find all classes that are based on that abstract class, find the one that matched the user's choice, instantiate it and pass it back to the calling code. Then the calling code would not need to care what came back and would just call the Execute() method on the object passed back. It was an elegant and performant solution that I was quite proud of. 


Last modified on 2012-07-22

comments powered by Disqus