Coding Concepts - Generics
Tags: webdev, typescript, beginners, javascript
Published: 2018-06-21 10:02:16

---
title: Coding Concepts - Generics
published: true
description: What are Generics, and why should we use them? 
tags: webdev, TypeScript, beginners, JavaScript
cover_image: https://thepracticaldev.s3.amazonaws.com/i/3hmvqjd7ozeoew2rd3gm.png
series: Coding Concepts
---

<h1>What are Generics, and why should we use them?</h1>
<blockquote><b>Generic programming</b> is a style of <a title="Computer programming" href="https://en.wikipedia.org/wiki/Computer_programming">computer programming</a> in which <a title="Algorithm" href="https://en.wikipedia.org/wiki/Algorithm">algorithms</a> are written in terms of <a title="Data type" href="https://en.wikipedia.org/wiki/Data_type">types</a> <i>to-be-specified-later</i> that are then <i>instantiated</i> when needed for specific types provided as <a title="Parameter (computer programming)" href="https://en.wikipedia.org/wiki/Parameter_(computer_programming)">parameters</a>. This approach, pioneered by <a title="ML (programming language)" href="https://en.wikipedia.org/wiki/ML_(programming_language)">ML</a> in 1973,<sup id="cite_ref-Lee2008_1-0" class="reference"><a href="https://en.wikipedia.org/wiki/Generic_programming#cite_note-Lee2008-1">[1]</a></sup><sup id="cite_ref-2" class="reference"><a href="https://en.wikipedia.org/wiki/Generic_programming#cite_note-2">[2]</a></sup> permits writing common <a class="mw-redirect" title="Function (computer science)" href="https://en.wikipedia.org/wiki/Function_(computer_science)">functions</a> or <a class="mw-redirect" title="Type (computer science)" href="https://en.wikipedia.org/wiki/Type_(computer_science)">types</a> that differ only in the set of types on which they operate when used, thus reducing <a title="Duplicate code" href="https://en.wikipedia.org/wiki/Duplicate_code">duplication</a>. Such software entities are known as <i>generics</i> in <a title="Ada (programming language)" href="https://en.wikipedia.org/wiki/Ada_(programming_language)">Ada</a>, <a title="C Sharp (programming language)" href="https://en.wikipedia.org/wiki/C_Sharp_(programming_language)">C#</a>, <a class="mw-redirect" title="Delphi (programming language)" href="https://en.wikipedia.org/wiki/Delphi_(programming_language)">Delphi</a>, <a title="Eiffel (programming language)" href="https://en.wikipedia.org/wiki/Eiffel_(programming_language)">Eiffel</a>, <a title="F Sharp (programming language)" href="https://en.wikipedia.org/wiki/F_Sharp_(programming_language)">F#</a>, <a title="Java (programming language)" href="https://en.wikipedia.org/wiki/Java_(programming_language)">Java</a>, <a title="Rust (programming language)" href="https://en.wikipedia.org/wiki/Rust_(programming_language)">Rust</a>, <a title="Swift (programming language)" href="https://en.wikipedia.org/wiki/Swift_(programming_language)">Swift</a>, <a title="TypeScript" href="https://en.wikipedia.org/wiki/TypeScript">TypeScript</a> and <a title="Visual Basic .NET" href="https://en.wikipedia.org/wiki/Visual_Basic_.NET">Visual Basic .NET</a>. They are known as <i><a title="Parametric polymorphism" href="https://en.wikipedia.org/wiki/Parametric_polymorphism">parametric polymorphism</a></i> in <a title="ML (programming language)" href="https://en.wikipedia.org/wiki/ML_(programming_language)">ML</a>, <a title="Scala (programming language)" href="https://en.wikipedia.org/wiki/Scala_(programming_language)">Scala</a>, <a title="Haskell (programming language)" href="https://en.wikipedia.org/wiki/Haskell_(programming_language)">Haskell</a> (the Haskell community also uses the term "generic" for a related but somewhat different concept) and <a title="Julia (programming language)" href="https://en.wikipedia.org/wiki/Julia_(programming_language)">Julia</a>; <i><a title="Template (C++)" href="https://en.wikipedia.org/wiki/Template_(C%2B%2B)">templates</a></i> in <a title="C++" href="https://en.wikipedia.org/wiki/C%2B%2B">C++</a> and <a title="D (programming language)" href="https://en.wikipedia.org/wiki/D_(programming_language)">D</a>; and <i>parameterized types</i> in the influential 1994 book <i><a class="mw-redirect" title="Design Patterns (book)" href="https://en.wikipedia.org/wiki/Design_Patterns_(book)">Design Patterns</a></i>.<sup id="cite_ref-GoF_3-0" class="reference"><a href="https://en.wikipedia.org/wiki/Generic_programming#cite_note-GoF-3">[3]</a></sup> The authors of <i>Design Patterns</i> note that this technique, especially when combined with <a class="mw-redirect" title="Delegation (programming)" href="https://en.wikipedia.org/wiki/Delegation_(programming)">delegation</a>, is very powerful, however, Dynamic, highly parameterized software is harder to understand than more static software.</blockquote>
So that's a bit of a long winded, and pretty non descriptive definition sourced from Wikipedia. I've been fascinated with Generics for a while, they can be quite hard to grasp, understanding why and where they should be used. The main motivation for the use of generics is to provide meaningful type constraints between members, Generics or Parametric Polymorphism,  are used in most programming languages, and although they can be harder to understand, there are 5 main benefits to using them.
<h2>Benefits</h2>
<ul>
 	<li>Stronger type checks at compile time.</li>
 	<li>Fixing compile-time errors is easier than fixing runtime errors</li>
 	<li>Elimination of casts. Which in turn is quicker.</li>
 	<li>Enabling coders to implement generic solutions, which can be reused for multiple purposes.</li>
 	<li>Future proofed for the datatypes of tomorrow.</li>
</ul>
Using a generic type is much more powerful than using standard types and allows us to create some form of encapsulation and well defined consistent API's. It doesn't matter how you use these, but it's a good to understand how to pass that type of information between different members, and that you can use them externally with return types which will give a more descriptive view of whats happening in your code.

In essence Generics just mean you can assign a Type to a Class. Hence the "T" we will see throughout this example.
<blockquote>Why use Generics? To abstract out data types, allowing you to reuse code and improve maintainability.</blockquote>
So let's run through a simple TypeScript example to show what I mean.
<h2>A Standard Class Example</h2>
We'll start with a <strong>non</strong> Generic List and switch it to a Generic List!

```javascript
class Stack
{
private stack: any[];
  pushItem(item){
  this.stack.push(item);
  }
}
```

This example above is a basic class which contains an <strong>Array</strong> called stack. Anything can be added to this array! Let's add a String, a number and a new person object.

```javascript

var newStack = Stack();
var aString = "A String";
var aNumber = 100;
var aPerson = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
newStack.pushItem(aString);
newStack.pushItem(aNumber);
newStack.pushItem(aPerson);
```

This will work, and maybe you want an array that can hold a mishmash of objects. However in most cases this will cause you a number of problems when iterating over the array, sorting, or filtering the values within. Worst of all, you won't know about these errors until runtime. These will not be found until the code executes, and therefore may not be found during testing.

Whereas with a Generic list will not let you add types to the Stack that it cannot deal with.
<blockquote>To use the generic container, you must assign the type of the container by specifying it at instantiation using the angle bracket notation.</blockquote>
It's actually pretty simple, let's look at the example from above but this time lets make 2 separate instances of our array, one that can hold numbers, and one that can hold strings. Firstly we'll need to create the Generic class.
<h2>The Generic Way</h2>
<img src="https://s3-eu-west-1.amazonaws.com/cdn.josephwoodward.co.uk/blog/cup_of_type_t_programming_mug.jpg" alt="Image result for cup type t" width="237" height="239" />

```javascript
class GenericStack<T>;
{
  private stack: T[]; 
  function pushItem(item: T) { 
  this.stack.push(item); 
  }
}
```

As you can see the code is pretty much identical to our example above! So what's all the fuss about? What benefit does this bring us? Well let's look at this example when initialising this new class.

```javascript
var numberStack = GenericStack<Number>(); 
var stringStack = GenericStack<String>(); 
var aString = "A String"; 
var aNumber = 100; 
var aPerson = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

// These will pass the typescript compiler
stringStack.pushItem(aString); 
numberStack.pushItem(aNumber);

// But these would all fail.
numberStack.pushItem(aPerson);
numberStack.pushItem(aString);
stringStack.pushItem(aPerson);
stringStack.pushItem(aNumber);
```

So what does this all mean? Well in essence we are have only created a single class, but have changed the behaviour of it depending on the Type referenced.  It's essentially a contract between the class and the type. Yes, we could have just created 2 separate classes, but then we'd be duplicating code.

Imagine if we'd create a Person class, rather than just a JObject, we could of created a <strong>GenericStack&lt;Person&gt;()</strong>

Now this is quite a trivial example, but type safety is quite a big deal, especially in JavaScript. As JavaScript is not a compiled language Typescript offers us the benefits of type safety and pre compilation to catch such errors.
<blockquote>As previously mentioned, without the Generic class, errors would only surface during run time.</blockquote>
A major part of development is building reusable, well defined components, If this class was to contain more functions, it could be re-used by teams across an organisation with minimum effort, allowing them to reuse their own types.
<h2>But does this not limit what you can do with Generics?</h2>
Well when you work with primitive types such as Strings and Numbers and even Arrays you will be familiar with certain methods available to you such as: <strong>.ToString()</strong> or <strong>.length() </strong>or <strong>.size() </strong>or <strong>.replace()</strong>

These require the compiler to know the type of the variables, unfortunately when using generics this will mean they cannot be used. The number type doesn't contain a <strong>replace() </strong>so you wouldn't be able to use it. And the <strong>T Type</strong> doesn't contain any of those listed above! A lot of people will try and implement Generics into their code just to say that they use them. The thing to make sure is that there is a use case for them. Generics come into play when you start moving away from using primitive data types (the basic data types available: numbers, string, etc.) and working with custom objects and classes.
<h3>Refactoring</h3>
Generics are  useful when refactoring your code, can you see instances in your code where you can abstract out the data type from the data structure?

If the answer is <strong>yes </strong>then you should be considering Generics!

There's a lot more to generics, and I'm not going to try and explain it all here, if you're interested in reading more about Generic, I've linked additional resources below which should paint a clearer picture.

<b>Have I missed something useful? Do you have anything extra to add? Have you used Generics in an interesting way? If so share below! </b>

Thanks for reading.

Chris
<h1>Additional Reading</h1>
<a href="http://www.typescriptlang.org/docs/handbook/generics.html" target="_blank" rel="noopener">Official TypeScript Documentation - Generics</a>

<a href="https://dzone.com/articles/hack-1-understanding-the-use-cases-of-generics" target="_blank" rel="noopener">Dzone - Understanding the use cases of Generics</a>

<a href="https://basarat.gitbooks.io/typescript/docs/types/generics.html" target="_blank" rel="noopener">Git Books - Generics</a>

<a href="https://code.tutsplus.com/tutorials/typescript-for-beginners-part-5-generics--cms-29603">Code.tutsplus. - Tutorials - Typescript-for-beginners</a>

&nbsp;