Abstract
- Also known as Parameterized Types or Generic Types
- Allow OOP Class and functions to be written in a way that is independent of specific Datatype
Code Re-usability
We don’t to duplicate the set of codes for each different Datatype.
Type Safety
Attention
Generics don’t work the same in all programming languages! See how the different languages implement generics below.
Code Specialisation
- The Compiler identifies each instance where you use that Generics and then generate source codes specific to that Datatype. Lastly, substitute the generic type with the generated type
Simplicity with power
The data is stored in the Virtual Memory exactly the way we expect it. And we can rip off the benefits of generics!
More resource demanding
Compiler takes a longer time to generate all the source codes and the resulting compiled code base is bigger.
Raw Type
- Without the generic type information, this exists for backward-compatible purposes. We should avoid using it, as it removes the type information that the compiler uses for type checking, which may result in runtime errors. However, there are specific cases where we may want to use the raw type (which I am still exploring)
Java Generics
- As shown below, instead creating an Array of values in Virtual Memory, it is actually creating an array of Pointer pointing to Memory Address that has the actual data
We can't create new Generic arrays!
Because generic types are the same regardless of their parameterised types. So that means we can swap the same class with different parameterised types which will result in a mismatched assignment like assigning an integer returned from the generic to a string. This will work if the parameterised type is string.
Bad for Caching
As you can see for array, the data is actually scattered around the memory. And this means we are unable to take advantage of Cache Locality and each element indexing takes 10-100 times longer! This is why Java is slower than system languages! Look at all the jumping around for the Linked List below.
Python Generics
- Similar to the implementation of Java Generics. The key difference is that the Array of Pointer in Python generics can point to objects of different Datatype. This explains why we can have flexibility to have different datatypes in the same array without affecting the ability to index! Because pointers are the same size, so we can perform indexing on the pointers, then obtain the value by perform Pointer Dereference on the pointer
Flexibility
We can have different datatypes in the same array!
Caution
Similar downside mentioned in Java Generics + no Type Safety.