Reflection in Programming Languages

View on LinkedIn


Reflection (uoᴉʇɔǝlɟǝᴚ) is a programming capability where a program can inspect, modify, and even call itself, especially in terms of its structures like objects, classes, and methods. Python, being a highly dynamic and introspective language, supports reflection very well. Go also supports reflection. Some languages, for instance C++, does not (see here why not).


Reflection saves a lot of time, when you do not need to specify the data types of attributes for certain methods. The example I wanna highlight is JSON serialization/deserialization, but the idea carries forward to some more scenarios.



Take the following 2 examples (images) in the attached images (courtesy ChatGPT).


The first one is Go, and the second one C++. For C++, you'll notice how we need to explicitly map values to fields for the JSON object. This might be a trouble in large projects because of the time it would take, the increased maintenance , and the limited dynamic behaviour.


If you have worked on a backend project, you probably know how often it is required to define the serialzer for your API requests and responses.


Also Python being a dynamic typed language, it allows for even more relaxation in defining the "structure" of the request/response, specially the response to be sent, as you might know you can just write a python dictionary to be a json response and python takes care of it.