Through all the months I’ve spent with the Java & C# code – I found especially one way of writing software can be extremely dangerous – would that be the darkest side of software engineering too?
And saying that I mean reflection – so powerful, so useful technique which sometimes shows itself as the only way to solve the problem…
Ok, speaking about that – why do I believe it can raise such big problems? Let’s speak about that …
- Analyzing statically typed code – nowadays all the powerful IDEs helps heavily to find the usages of code we would like to change or just to find dead code. Whenever you use reflection (or even better – hidden reflection) it can
easily provide to unwanted scenarios when you remove production code, or change the contract which was updated in all the places besides of the reflection points …
- KISS, Readability – did you use reflection? Yes, it probably means you broken few paradigms we should follow in writing clean code. Whenever someone will maintain the code, or just go through it – it will take much more time to understand it (readability) and for sure, it will be not the simplest solution you would expect to find in the code (but maybe it’s the only solution? Let’s hope so …).
- Being slow, and often hidden – it can drive to have problems with performance or memory (creating many instances, keeping somewhere active pointers) – it will probably show itself at some point but in the runtime – not that obvious when looking through the codebase (especially bigger one), even when you looked through the reflection code.
There would be probably more cases, but at least that can show you possible challenges coming from using it. Now, below you can see my categories of how bad can be reflection!
- Bad bad bad bad reflection – hidden reflection which has no supporting it unit tests!
- Bad bad bad reflection – reflection which maybe is not that hidden, but still has no supporting it unit tests.
- Bad bad reflection – hidden reflection (in prod code) which is transparently documented through unit test specs.
- Bad reflection – reflection fully covered by unit tests.
I understand that there are cases that languages like Java or C# do not allow you to solve the problem in other way – but foremost – remember to never write reflection, or even worse to hide it, and (the most important) always cover that particular code with good unit tests, documenting the valid use case for it, breaking if any dependent/used contract is changed or if any possible case can be broken in runtime – being always not that obvious even when you do code reviews.