Saturday, June 26, 2010

Generics

Generics this generics that. Surely, generics were one of the main hits of .Net FW 2.0 and you all know the advantages they give you, but what about disadvantages? The books I've read on software development are hardly giving anything for disadvantages, and that's suspicios because nothing is ideal and if you gain something, that means losing something the very same moment you gain.

The pain in the ass generics give you can be described as follows:
- generic classes and interfaces with more than two type parameters are hard to understand and maintain;
- generic class, say, List<B> is not convertible to List<A> if B is subclass of A (as of .Net FW 3.5), moreover there is no direct relationship between List<A> and List<B> which could be described in terms of OO paradigm;
- generics cypher the code to some extent: when you see an instance of Mine.MyGenericType<Mine.MyType1, Mine.MyType2, Mine.MyType2> in code you have to scratch your head to figure out which parameter means what, because they only have names internal to MyGenericType and don't mean anything outside of that class (this is somewhat less of a problem when you are writing the code, thanks to intellisense);
- generics used solely for type safety scare me a bit: the main drivers for introducing generics were code reuse, type safety and performance (in that order). There is usually a way or two to avoid using generics without losing type safety.

That's my humble opinion and don't get me wrong, I absolutely love generics. Just make sure you don't rely on them too much.

No comments:

Post a Comment