Use generics or not?

A simple question arises regarding the use of generics or not, and if so, is this the right way?

A typical non-generic version looks like this:

public interface IFood { string name { get; set; } } public class Vegetables : IFood { #region IFood Members public string name { get { return "Cabbage"; } set{ } } #endregion } public class Cow { private IFood _food; public Cow(IFood food) { _food = food; } public string Eat() { return "I am eating " + _food.name; } } 

The general version is as follows:

  public class Cow<T> where T : IFood { private T _food; public Cow(T food) { _food = food } public string Eat() { return "I am eating " + _food.name; } } 

Am I doing everything right in the generic version? Do I need to use a universal version for future growth? This is just a simple layout of the source script, but it is completely reminiscent.

+4
source share
3 answers

I think this is a bad idea in this particular example.

A List<int> often described as a List of int. A Cow<IFood> harder to describe - this, of course, is not an IFood cow. This is not a slunk dunk argument, but shows a potential problem.

MSDN :

Use generic types to maximize code reuse, security type, and performance.

In your example, the generic version does not have code reuse, does not require additional security, and does not improve performance.

+10
source

I think it’s a very bad idea to use generics to enforce behavior. If you want a cow to be able to eat vegetables, then this is more logical and should be applied by logical rules, rather than trying to force the compiler to enforce it. Thus, the cow must accept all the products, and then the application logic determines what to do if you gave her something other than what she can eat.

A good example of this is that if you decide to add Hay as something that a cow can eat, there is no way to use generics to say that you can give a cow Vegetables or Hay if you don't create an IVegetableOrHay interface that should force we all want to just kill this cow and eat it for dinner.

Casting the compiler to ensure the correct structure of the program. The application logic belongs to the code.

+3
source

Do you want to extend / implement subclasses using generic ones? Then this is not the goal of Generic. You will use generic, where all types of objects have the same goal. Like serialization. Here, if you are creating a generic COW movie, you need to implement a subclass of the COW function inside COW. which will not refuse to acquire another subclass. Here COW can be a superclass, not a general one. my advice is to use common to different classes. Not within the same family of classes.

+1
source

Source: https://habr.com/ru/post/1381617/


All Articles