Generics – What is Generics Abuse?

generics

While reviewing some code, I noticed the opportunity to change it to use generics. The (obfuscated) code looks like:

public void DoAllTheThings(Type typeOfTarget, object[] possibleTargets)
{
    var someProperty = typeOfTarget.GetProperty(possibleTargets[0]);
    ...
}

This code could be replaced by generics, like so:

public void DoAllTheThings<T>(object[] possibleTargets[0])
{
    var someProperty = type(T).getProperty(possibleTargets[0]);
    ...
}

In researching the benefits and shortcomings of this approach I found a term called generic abuse. See:

My question comes in two parts:

  1. Are there any benefits to moving to generics like this? (Performance? Readability?)
  2. What is Generics Abuse? And is using a generic every time there is a type parameter an abuse?

Best Answer

When generics are appropriately applied, they remove code instead of just rearranging it. Primarily, the code that generics are best at removing is typecasts, reflection, and dynamic typing. Therefore generics abuse could be loosely defined as creating generic code without significant reduction in typecasting, reflection, or dynamic typing compared to a non-generic implementation.

In regard to your example, I would expect an appropriate use of generics to change the object[] to a T[] or similar, and avoid Type or type altogether. That might require significant refactoring elsewhere, but if using generics is appropriate in this case, it should end up simpler overall when you're done.