Interface (contract), Generics (universality), and extension methods (ease of use). Is it a right design?
Posted
by
Saeed Neamati
on Programmers
See other posts from Programmers
or by Saeed Neamati
Published on 2014-08-21T10:26:00Z
Indexed on
2014/08/21
10:29 UTC
Read the original article
Hit count: 217
I'm trying to design a simple conversion framework based on these requirements:
- All developers should follow a predefined set of rules to convert from the source entity to the target entity
- Some overall policies should be able to be applied in a central place, without interference with developers' code
- Both the creation of converters and usage of converter classes should be easy
To solve these problems in C# language, A thought came to my mind. I'm writing it here, though it doesn't compile at all. But let's assume that C# compiles this code:
I'll create a generic interface called IConverter
public interface IConverter<TSource, TTarget>
where TSource : class, new()
where TTarget : class, new()
{
TTarget Convert(TSource source);
List<TTarget> Convert(List<TSource> sourceItems);
}
Developers would implement this interface to create converters. For example:
public class PhoneToCommunicationChannelConverter : IConverter<Phone, CommunicationChannle>
{
public CommunicationChannel Convert(Phone phone)
{
// conversion logic
}
public List<CommunicationChannel> Convert(List<Phone> phones)
{
// conversion logic
}
}
And to make the usage of this conversion class easier, imagine that we add static
and this
keywords to methods to turn them into Extension Methods, and use them this way:
List<Phone> phones = GetPhones();
List<CommunicationChannel> channels = phones.Convert();
However, this doesn't even compile. With those requirements, I can think of some other designs, but they each lack an aspect. Either the implementation would become more difficult or chaotic and out of control, or the usage would become truly hard. Is this design right at all? What alternatives I might have to achieve those requirements?
© Programmers or respective owner