Friday, December 4, 2015

Tiny Improvements - C# - Don't use Reflection

Reflection is an .Net API that allows you to load and work with code you do not have references to. It allows you to enter the names of an assembly and a type as a string and then create that object. Reflection is incredibly useful for building code which works on code and is vital for plugin architectures, frameworks, and ORMs. It is not a good tool for application developers.

Programmers love to be cool and use neat features to make neat code. This leads them to using reflection. I have worked on multiple applications that used reflection. It has lead me to the conclusion that you almost never want to use reflection in application level programming.

If you are writing a framework, an ORM, or basically something that works with other people's code, go ahead and use reflection. If it is an application the developer will always know what code is going to be loaded. That means you never need to use reflection. Say you are going to create some object, but you may be creating one of any number of different objects that meet an interface. This calls for a simple factory that had a simple map in it, not reflection. Say you want to easily add new components that meet an interface. That calls for adding the class name to a list and not reflection.

So why am I saying this? Why shouldn't you use reflection?

1) It is confusing to people. It is hard to see what classes are being used and how they are created is much more complex

2) It offers no value. If what you are doing could be done without reflection then reflection has no value. If you control all the code then reflection has no value.

3) It obsfucates assembly and class dependencies to programmers and tools. We have a large number of tools to analyze code. Those tools get hamstrung by reflection because it hides dependencies.

Almost anything an application level developer can do with reflection, they can do more easily without it. It is a neat toy and it is really cool to use, but don't use it. You could say that reflection decouples code and that that is good, but really you are just hiding the references so you are not decoupling code, you and just hiding the coupling.

Confession: I, as an application level developer, have used reflection. I used it to access internal, private, or protected members of library objects. It was some messed up stuff and I would not recommended doing that, but the Sharepoint APIs made me do it...

No comments:

Post a Comment