redman
redman

Reputation: 1521

When not to implement a generic interface?

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!

Upvotes: 3

Views: 165

Answers (2)

LBushkin
LBushkin

Reputation: 131676

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.

Upvotes: 3

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

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?

Upvotes: 3

Related Questions