Reflection in Programming – Are There Problems with Using Reflection?

Architecturecode-qualitydesignprogramming practices

I don't know why, but I always feel like I am "cheating" when I use reflection – maybe it is because of the performance hit I know I am taking.

Part of me says, if it is part of the language you are using and it can accomplish what you are trying to do, then why not use it. The other part of me says, there has to be a way I can do this without using reflection. I guess maybe it depends on the situation.

What are the potential issues I need to look out for when using reflection and how concerned should I be about them? How much effort is it worth spending to try to find a more conventional solution?

Best Answer

No, it's not cheating - it is a way to solve problems in some programming languages.

Now, it is often not the best (cleanest, simplest, easiest to maintain) solution. If there is a better way, use that one indeed. However, sometimes there isn't. Or if there is, it is just so much more complex, involving a lot of code duplication etc. which makes it infeasible (difficult to maintain in the long run).

Two examples from our current project (Java):

  • some of our testing tools use reflection to load configuration from XML files. The class to be initialized has specific fields, and the config loader uses reflection to match the XML element named fieldX to the appropriate field in the class, and to initialize the latter. In some cases, it can build a simple GUI dialog box out of the identified properties on the fly. Without reflection, this would take hundreds of lines of code across several applications. So reflection helped us put together a simple tool quickly, without much fuss, and enabled us to focus on the important part (regression testing our web app, analysing server logs, etc.) rather than the irrelevant.
  • one module of our legacy web app was meant to export/import data from DB tables to Excel sheets and back. It contained a lot of duplicated code, where of course the duplications were not exactly the same, some of them contained bugs etc. Using reflection, introspection and annotations, I managed to eliminate most of the duplication, cutting down the amount of code from over 5K to below 2.4K, while making the code more robust and way easier to maintain or extend. Now that module ceased to be a problem to us - thanks to the judicious use of reflection.

The bottom line is, like any powerful tool, reflection too can be used to shoot yourself in the foot. If you learn when and how (not) to use it, it can bring you elegant and clean solutions to otherwise difficult problems. If you abuse it, you can turn an otherwise simple problem into a complex and ugly mess.

Related Topic