Note that there are some explanatory texts on larger screens.

plurals
  1. POUse-cases for reflection
    text
    copied!<p>Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing.</p> <p>Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with:</p> <ol> <li><p>Given a config file with lines like<br> x = "Hello World!"<br> y = 5.0<br> dynamically set the fields of some <code>config</code> object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.)</p></li> <li><p>When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request.</p></li> <li><p>When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate<br> <code>!some_command arg1 arg2</code><br> into a method call <code>actions.some_command(arg1, arg2)</code> and print whatever that function returned back to the IRC channel.</p></li> <li><p>When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy.</p></li> </ol> <p>So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload