Find the use of a specific method when called with a specific subtype

I am refactoring troubles from a large code base and need to find where a particular method that accepts instances of a fairly common interface is called with a specific implementation of that interface.

For example, NastyStatic uses the DoBadThings(IBusinessObject) method. I have about 50 classes that implement IBusinessObject in my business library, including DontHurtMe : IBusinessObject .

How can I find every call to NastyStatic.DoBadThings(foo) , but only where foo is an instance of DontHurtMe ?

EDIT: I am using some kind of static analysis tool. Installing a dynamic clock in DoBadThings (or similar) and launching the application is not really an option. It will already throw an exception due to the changes I made to DontHurtMe , and there are too many code paths to find all the ways to use it that way (at least until it starts living and my users start complaining).

+4
source share
3 answers

Easy. Write a DoBadThings overload that takes the DontHurtMe parameter as a parameter. Now let's see what it's called. This will not determine when a method is called with an declared IBusinessObject, which is DontHurtMe, but I do not think that static analysis can detect this. This gets all calls to your method with the declared DontHurtMe.

+5
source

ReSharper 5 Structural Search can do this. Assume the following code:

 class Program { static void Main(string[] args) { var hm = new HurtMe(); var dhm = new DontHurtMe(); DoBadThings(hm); DoBadThings(dhm); } static void DoBadThings(IBusinessObject ibo) { } } interface IBusinessObject { } class DontHurtMe : IBusinessObject { } class HurtMe : IBusinessObject { } 

Now, as noted, R # Find Usages on DoBadThings , no matter what parameters we specify, will find both calls in Main .

But if we

  • Go to ReSharper | Find | Search with Pattern.... ReSharper | Find | Search with Pattern....
  • Add Placeholder | Expression , name it dhm and specify DontHurtMe as type
  • In the Search pattern enter DoBadThings($dbm$)
  • Click Find

we get in our results only a call to DoBadThings object with a type statically identified as a DontHurtMe , and not a call to a HurtMe .


I like the accuracy of the procedure suggested by @Carl Manaster, but this method makes it possible when you cannot overload this method.

+2
source

I can not find a solution for static analysis. I just tried the ReSharper options "Advanced Search ..." and found nothing. You can set a conditional control point on this method with a condition like foo is DontHurtMe , but I suppose you already know that this is better for cases when you are trying to find an error than for refactoring purposes.

0
source

Source: https://habr.com/ru/post/1340135/


All Articles