Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird use of generics

Tags:

c#

generics

After a bit of programming one of my classes used generics in a way I never seen before. I would like some opinions of this, if it's bad coding or not.

abstract class Base<T> : where T : Base<T>
{
    // omitted methods and properties.
    virtual void CopyTo(T instance) { /*code*/ }
}

class Derived : Base<Derived>
{
    override void CopyTo(Derived instance)
    { 
         base.CopyTo(instance);
         // copy remaining stuff here
    }
}

is this an OK use of generics or not? I'm mostly thinking about the constraint to "itself". I sometimes feel like generics can "explode" to other classes where I use the Base class.

like image 874
KTrum Avatar asked May 25 '10 08:05

KTrum


People also ask

What are the uses of generics?

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.

Why didnt Go have generics?

As we are all aware Go has no Generics, it was designed with simplicity in mind and Generics as mentioned above is considered to add complexity to the language. The same goes for Inheritance, Polymorphism and some other features that the top object-oriented languages showed when Go was created.

Are generics slow Java?

Generics do not affect runtime performance.

What are advantages of generics?

Generics shift the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced. Better performance.


1 Answers

Yes, this is reasonable - I have something similar in my Protocol Buffers port (except more complicated, as there are two mutually referenced types).

You're absolutely right about generics sometimes ending up spreading across the code-base - what you've done here means that bits of code which only care about Derived having an appropriate API don't need to worry about the generics.

My advice is to try to keep it simple where possible, but in cases where an "odd" generic constraint really does describe what you want, go for it. You should be aware that this doesn't force valid use though - you could easily have:

class Banana : Base<Derived>

and that would be valid, though odd and probably unexpected to users.

You might also want to consider sealing Derived here - if you derive further, you're again likely to end up with odd behavior (or at least an odd API).

like image 182
Jon Skeet Avatar answered Oct 06 '22 01:10

Jon Skeet