I have an interface named IDeviceId that I use in my domain. I also have several concrete classes that implement IDeviceId. Each concrete class contains the logic for a specific type of DeviceId. For example, I have DeviceMacId, which is simply a valid MAC address. Another concrete class is DeviceShortMacId, which takes the last 6 digits of a valid MAC address and combines it with a fixed 6-character prefix to create a valid MAC (several legacy apps use only the last 6 digits). I have a few other classes for expressing an ID, but the majority of them are all derivatives of the same data.
I’d like to be able to easily convert from any one of these classes to another. My first thought was to create a static class and do something like DeviceIdConverter.ToDeviceShortMacId(IDeviceId).
What’s the best way be able to easily accept data in one form, and then convert it to another in a repeatable fashion (across multiple apps)?
I don’t think there is a “best way” to do this, you’re going to have to find a pattern that works for you and go with it.
Off the top of my head, based on the examples you presented I would do something like:
Then each of the classes would need to implement the conversion methods. Now if you plan on adding a lot of other implementation (concrete) classes later, then this could get pretty verbose. So what you might consider in that case is in each of the projects which creates a new implementation you also create extension methods like:
The extension methods approach is a lot more modular, but could also be a lot more code.