Thursday, April 17, 2008

When are there just too many generics?

Generics are a pretty cool language feature. They provide type safety and felxible reuse at the same time, and I reckon that's pretty cool. However as with all the other cool language features - like implicit typing, you need to be responsible with them. The question is though, when do you have too many generics?

One of the peices of code I wrote this week was a generic entity retrieval command. I already had a command signature that looked a little like this:

internal void MyCommand : Command <TRequest,TResponse>

No problems here. A request, a response.Now this was ok, but I couldn't really get an entity of any type like this. I tried putting the type in the request as a parameter, but it didn't really work. So then I moved to this..

internal void MyCommand<TEntityType> : Command <TRequest,TResponse>

Now I've got 3 generic parameters. 1 that specifies the type of entity I'm requesting, and 1 each for the request and response types. I might be getting a bit zesty with my generics. However this lets me go and get a table from my context like so:

Table<TEntityType> myQueryTable = myDataContext.GetTable<TEntityType>

Which is nice I think, as it lends itself to almost any table that you've got mapped in your data context.

Now, in case there weren't already enough generics in my class definition, I also needed to know what type I was returning in my response! So....

internal void MyCommand<TEntityType> : Command<TRequest,TResponse<TEntityType>>
So I really still only have 3 types here, but now I have the TEntityType on the response as well. Do I have too many generics? Am I creating a readability and maintainability issue here? I'm eagerly awaiting the code review on this one actually... I'm interested to see what is said.

What do you think? 1 too many? 2 too many? What the hell am I doing? Would you have done it differently?

1 comments:

Anonymous said...

Mr. Steve,

I think there may be a bit of a problem with the way you are using generics. If you post the code it will be easier to give some advice.

YVSKV