I have an array of different object types (about 15 different types) , they are coming from 3rd party system.
For every type I need to make different transformation.
My original thought is to make some interface with transform function and for every type make a class and run it’s own implementation.
But like this I will need to make a really big if statement that checks the object type and make the mapping.
I am trying to learn something new here, so my question is there other ways to deal with this situation?
Have you considered the possibility of using a Visitor?
If you combine the visitor pattern with the use of
dynamic, you could get a pretty simple implementation without anyiforswitchstatements, or having to manually create a Type Dictionary with delegates, or similar alternatives.Using
dynamicyou can avoid implementing the “accept” part of the design pattern, which I assume is useful to you since these are external types you have no control over.Meaning, you create something like this:
You implement that visitor, and can later call the implementation using:
You would probably have to handle for exceptions regarding not having an appropriate overload for the
Type.That would solve the part of the problem related to executing a separate method for each type.
Now, depending on what you specifically need to do with each one, if you need automatic property mapping then AutoMapper could be very useful.