DEV Community

Discussion on: Explain Generics Like I'm Five

Collapse
 
alainvanhout profile image
Alain Van Hout

Everybody likes stories and adventures. You yourself like them so much, that your father drew a story book specifically for you, where the main character goes on a journey and encounters lots of new and interesting things.

Now, you like unicorns, so the book your father drew for you has a unicorn as the main character. Your sister also really likes the story, but she prefers dragons to unicorns, so your father recreates the entire book, but with a dragon as the main character. Your best friend also really likes the story, but he'd like labrador as the main character, so your father obliges and draws yet another version of the story. Sounds like a lot of work, right?

Well 'generics' is as if your father made single book, but left a hole on every page, in such a way that you can place a picture of your main character of choice on the back of the book (exactly where all the holes line up), and suddenly the whole story is about your main character. From now on, all you need to do is make a main character for yourself, and you can have your very own version of the story, with no effort whatsoever.

Collapse
 
thermatix profile image
Martin Becker

I think this is the best explanation, but you might want to add how this maps to code as this is very abstracted away from code.

Collapse
 
alainvanhout profile image
Alain Van Hout • Edited

Given that this is an #explainlikeimfive post, abstracting away from the code is rather a fundamental requirement :).

But for completeness sake: the original books would have been the UnicornBook, DragonBook and LabradorBook classes, which are nearly identical expect wherever the Unicorn, Dragon or Labrador classes (or their instances) are used. The generic equivalent would ba a Book where T can be added for whatever you like, to create e.g. Book< Unicorn > or Book< Eagle >.

Hope that helps :-).

Thread Thread
 
thermatix profile image
Martin Becker

Heh, totally get where your coming from.

Collapse
 
trinini93 profile image
Trina Chowdhury

The best explanation, hands down. I'm a new developer and have been trying to understand generics for days, and no other explanation was easier to understand than this. Thank you.