2

Working with legacy moderate size project. I have implemented one feature using Decorator pattern, and it works great except that it breaks crappy code that uses downcast from interface to implementation. The question is: is there any tool or compiler flag or something, that can help me find all cases of using downcast. It is ok for me to find all cases for all types.

I have some code to elaborate my problem:

there were

interface IComponent {}
class Concrete : IComponent {}
...
IComponent obj = new Concrete()

and now

interface IComponent {}
class Concrete : IComponent {}
class Decorator : IComponent
{
   private IComponent _imp = new Concrete()
}
...
IComponent obj = new Decorator()

and bad code breaks on casting obj to Concrete, like (Concrete) obj.

capone
  • 728
  • 5
  • 17
  • How does `(Concrete)obj` break your code? `obj` is a `Concrete` so the cast should work at run time. Did you mean that you are casting to `Concrete` when it's actually a `Decorator`? Either way down casting is a bit of a code smell. – juharr Oct 23 '15 at 19:50
  • If `Concrete` isn't sealed why not just use it as your base instead of `IComponent` – Matthew Whited Oct 23 '15 at 20:09
  • If you want `Decorator` to be used 100% differently than `Concrete` when used as IComponent then just explicitly implement `IComponent` – Matthew Whited Oct 23 '15 at 20:11
  • @juharr Sorry, my original code snipped was not correct. I have fixed it. I think the problem is obvious now – capone Oct 23 '15 at 20:29

2 Answers2

5

Temporarily mark Concrete with ObsoleteAttribute. Then check the Errors List in Visual Studio for warnings about using obsolete code. Double clicking these will take you to the code that is using Concrete.

Bradley Uffner
  • 16,641
  • 3
  • 39
  • 76
0

You could also write a custom Code Analyzer if you are using Visual Studio 2015. This would give you incredible control over code validation rules. It's a bit on the complex side though. Details can be found here https://msdn.microsoft.com/en-us/magazine/mt573715.aspx

Bradley Uffner
  • 16,641
  • 3
  • 39
  • 76