What Is Reflection

The translation of the term “reflection” is rather confusing — it always feels like you’re taking the word at face value.

An Example

I wrote a hash calculator, which contains the following code:

1
2
3
4
5
6
if selected_algorithm == "SHA-512":
    algorithm = hashlib.sha512()
elif selected_algorithm == "SHA-256":
    algorithm = hashlib.sha256()
else:
    algorithm = hashlib.md5()

This code simply creates the corresponding object based on the digest algorithm the user selected — a fairly typical factory method.

But I still find it a bit troublesome. Can it be made simpler? That’s where reflection steps in:

1
2
3
4
if hasattr(hashlib, selected_algorithm):
    algorithm = getattr(hashlib, selected_algorithm)()
else:
    algorithm = hashlib.md5()

Previously, every new digest algorithm had to be hard-coded into the program as an extra branch; with reflection, however, you can look up the corresponding method in reverse from the selected string and call it at runtime, just like rewriting the source code.

So, Gul’dan, what’s the price? The price is merely losing a bit of efficiency. Many Java frameworks make heavy use of reflection, such as the well-known Spring.

Some materials that explain reflection say it can ignore encapsulation and forcibly access the members of classes and objects. I don’t think that’s a good practice. If a member needs to be accessed, then there’s no need to make it private or protected; and if you truly must do so, you’d better think about whether there’s a problem with your architecture and whether it should be changed.

About C++ and Reflection

Anyway, as of the C++ 20 standard this mechanism still hasn’t been added, though there is a keyword typeid that carries a hint of reflection. Maybe it will be added in a future standard.

In summary, this mechanism isn’t a necessity, but it does reduce code complexity in certain application scenarios — just use it as needed.

In programming, the first step is seeing a mountain as a mountain — knowing the usage and the mechanism; the second step is seeing a mountain not as a mountain — knowing when not to use it; the third step is seeing a mountain as a mountain again — knowing why to use it and why not, and reaching for it effortlessly with ease.