tags:

views:

78

answers:

2

Is there a general rule for when you should and shouldn't have a generic interface?

My case in point is a simple data frame interface. There is a "user data" member to allow the implementation to attach any implementation-specific data that needs to go with the frame. I don't know whether to leave it as an object type (and require them to cast it) or to have the interface be generic for this single member so the compiler will catch bad usage.

If it becomes generic, then a lineage of usage needs to also be generic to get the type passed down the line (if that makes sense). It seems like a lot of work for this one member, which is the basis of my question.

Thanks!

+3  A: 

Questions to consider when making your decision:

  1. Is it an error to store any object in this data member? (For example, are you expecting/requiring a string, or would an int suffice?)

  2. How many different types of data objects do you expect to be used? Do they have a common interface or base class?

  3. Is this class currently being used, and will changing it break those other classes that use it?

Kyle Trauberman
Don't buy this. Especially the first point considering there are constraints to limit the types that can be used.
Finglas
Hey Dockers, I'm not sure I understand your comment. Maybe I need to clarify point 1?
Kyle Trauberman
+3  A: 

One area where generics tend to break down a bit is with heterogeneous collections. If your data frame objects will be combined into a single collection type to be passed around, you may find it hard to apply generics. Particularly since in the example you provide, there doesn't seem to be a base type that all "user data" will inherit from, other than object.

In fact, in these types of problems, you may find yourself defining both a generic interface as well as a non-generic version, just so that you can pass types around polymorphically.

Generics are powerful and very useful, but in the example you describe, I suspect they may be more trouble then they're worth.

LBushkin
Why would you need to create both a generic and non-generic version? If you need a non-generic version, couldn't you just use the generic version but with `object` as the parameter, e.g. `List<object>`?
Mark Byers
Cleaner code, I would imagine. Many if not most .NET developers consider it a code smell when `System.Object` is used as the generic type parameter.
Aaronaught
@Mark: The main reason you often need a non-generic interface is so that you can create collections that refer to the interface. Rules for generics preclude you from storing an `ISomething<object>` into a `IList<ISomething<MyClass>>` even though MyClass clearly is an object. To deal with this, you often need a non-generic ISomething interface just to be able to create heterogenous collections.
LBushkin
+1 for heterogeneous collections. That is a very good point and something I did not consider.
oakskc