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:
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>>
What do you think? 1 too many? 2 too many? What the hell am I doing? Would you have done it differently?