mardi 28 juillet 2015

When to use generics and type checking?

Assume A through Z to be 26 classes I defined. In the following example:

  private List<A> _listA;
  private List<B> _listB;
  // private List<C>, and so on, through...
  private List<Z> _listZ;

  private void setLabelA()
  {
      LabelA.Text = _listA.Count;
  }

  // private void setLabelB() exists
  // and so does setLabelC()
  // and so on, all the way through to...

  private void setLabelZ()
  {
      LabelA.Text = _listZ.Count;
  }

It seems to me that there is no way to shorten this other than the following:

  private void setLabel<genericType>(List<genericType> list)
  {
      if(list is List<A>)      LabelA.Text = _listA.Count;
      else if(list is List<B>) LabelB.Text = _listB.Count;
      else if(list is List<C>) LabelC.Text = _listC.Count;
      //  and so on...
      else if(list is List<Z>) LabelZ.Text = _listZ.Count;
  }

Overloading the function name doesn't reduce the number of lines of code:

  private void setLabel(List<A> list)
  {
      LabelA.Text = _listA.Count;
  }

  private void setLabel(List<B> list)
  {
      LabelB.Text = _listB.Count;
  }

I prefer to use the is operator to determine which Label to set, because it preserves space (in this scenario, 50 lines of meaningless brackets and 25 lines of slightly-different function names). However, a Stack Overflow user recommended that I not use generics, and instead use separate functions, one for each Label. Although this solution will work, I prefer to not do so.

Is there any benefit towards NOT using the is operator, and towards explicitly typing my functions?





Aucun commentaire:

Enregistrer un commentaire