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):
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.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.