Lior Ohana
Lior Ohana

Reputation: 3527

Using Reflection for Accessing Private Members

Short story. Someone in a project I'm involved in, decided to use reflection for accessing a member of another class from another DLL. Why? laziness. I have a good (bad?) habit of eliminating all Resharper warnings before checking in files. One day, I saw a private member that was not used anywhere in the class it belonged to...so, shift+delete and the member is gone. Two months after, a showstopper from one of our production sites. It took us 1 week to find our that the problem was that the reflection code could not find the private member and wrapping code was not good enough. By happen, it was also a scenario that was not covered by our automatic testing.

Which code analysis tool do you recommend where I can setup rules for such use cases?

Thanks

Upvotes: 0

Views: 613

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127603

There is no tool as there is no way to test for this on the DLL side of things.

The reason you keep some methods are public and some methods are private is so you can have a published contract that people consuming your DLL can use. What you do internally in your DLL should be a black box that no one should have any knowledge or caring about what is happening.

The only way to "test" for this is on the caller side writing bog standard unit tests for any function that uses reflection. Then you must make sure the shipping version of the DLL matches the version you did your unit tests against.

As for the person who used reflection, have him justify his reasons and if not statisfactory put him on probation requiring all code he submits to be reviewed more thoroughly before it is allowed to be checked in. If he does not stop doing things like this (either using reflection when he absolutely should not, or not writing through unit tests for his code that must use reflection to be sure that the code he is calling has not changed internally) he should be fired.

Upvotes: 4

Related Questions