Generics
What exactly are generics and why should we use them?
Generics aren’t daunting because of what they are but because of how complicated they get. Breaking them into concrete implementations and renaming type variables can help.
What are they?
A generic type is one that allows developers to build general functionality not bound to a specific type. The generic defines what other types can be used with it. Here is an example of a simple collection generic:
Why are they hard?
I think the difficulty in generics comes from bad type variable naming or overly complex types. You usually see type variables names T
or U
(like in my example above).
TCollectable
is more explicit. It adds context to the T
type variable: something collectable.
Here is how we use of the above type with the TCollectable
as string
:
Here is a more complex generic:
A real example in C#. This represents a function with 6 parameters that are different types. The naming is poor as each param is just Tn
. Better naming might help (e.g. TFirstParamter, TSecondParamter
) at least to understand what’s happening. In this example refactoring to a type with more context makes sense:
I find it easier to understand a single type of ManyOptions
vs six different, unrelated, types.
Why use generics?
Mostly to save code. You don’t need to change the collection code when you change the type of TCollectable
. A string-only collection looks like:
It’s clear that code isn’t specific to strings. Generics can share code without re-implementing anything.
Here is an example on repl.it.