Is this bad practice? Overloading methods for generic interface and returning different types
As a follow-up to this question:
Is a bad practice to Return di开发者_Python百科fferent types when overloading a method?I am thinking about a very simple mapper interface I'm using:
public interface IMap<T,U>
{
U MapFrom(T obj);
T MapFrom(U obj);
}
This is perhaps a more targeted example of the noted question's discussion. An instance implementing this interface just maps between types.
I could do it this way:public interface IMap<T,U>
{
U MapRight(T obj);
T MapLeft(U obj);
}
but that seems silly because, conceptually, the notion of to and from don't really apply to my generic mapper here. It's just a bidirectional map. So, to compliment the linked question:
Is this generic map bad practice?How should I name methods to avoid returning different types without compromising the "genericness" of the interface?
EDIT: Also, in response to an answer, this is for mapper (not that it's really relevant). I just don't include the mapping method in the interface.
EDIT2: I suppose the same question would apply if I had a single-direction mapper (or adapter) then I implemented it twice for the two directions... same method name, different return type.
That's tough because you have no way of restricting T and U to not be the same type, so you always run the risk of having them be the same. I'd say you need to just find two names you can live with, like:
- MapFirst
- MapSecond
Or:
- Map
- ReverseMap
Or:
- Forward
- Reverse
First, you're not mapping, you're converting. There's a difference. Mapping is what a dictionary does. Converting is what happens when you put in one type and get a different one out.
I would create the interface like this:
interface IConvertible<TSource, TResult>
{
TResult Convert(TSource source);
}
You want two way conversion? Great. Implement both IConvertible and IConvertible. Want to encapsulate that into a single interface? Great, create ITwoWayConvertible and implement both.
精彩评论