[fpc-devel] Generics Basics
chrivers at iversen-net.dk
Tue Nov 8 22:45:27 CET 2005
On Tuesday 08 November 2005 21:33, L505 wrote:
> >I am trying to understand what exactly generics are. I read the wiki
> >page, but there are lot's of code examples and very few explanations.
> >Can someone explain it to me in a (relatively) simple way?
> >What problem is it trying to solve?
> >And how do generics relate to interfaces?
> I had the same problem for a few years. It took me a few months/years to
> first diagnose "what the fudge" templates/generics actually were, and what
> problem they exactly solved. All the information about generics is pretty
> non-real world and non-case study on the internet. It is also hyped by
> programmers who again seem to show no real world or case studies. But I can
> see how they can be useful in theory, nevertheless.
> I'm not going to give you a technical explanation on what they are, because
> someone else can do that (and I don't have experience with generics, so I'm
> not qualified to do so).
> Here is a vague non-technical explanation:
> Basically generics helps you save some Typing and syntax in your units. You
> can address several things at once with the same Type. Supposedly, this
> encourages code reuse. You can address and create things via a shortcut
> syntax sort of way.
The Very Big Advantage (Tm), is that you get syntax checking, while still
using a type diversely. That's impossible to do (at compile-time) without
Probably the best example of this is something like TList:
TOrange = class ... end;
TApple = class ... end;
T := TList.Create();
// Whoops, what was that? Now our program might crash.
Of course, we could create a specialized TAppleList that only accepts Apples,
but that's boring and hard work. A much cleaner way is generics:
T := TList<TApple>.Create();
// This wont compile! The problem is prevented at compile-time!
I hope that answers your question as to why it's a good idea :-)
More information about the fpc-devel