Edgroom's Educators Excellence Awards - 2024

EdBlogs

How to design Generic classes?

How to design Generic classes?

This article talks about how to design Generic classes at a basic level. Beginners feel comfortable in using Generic classes but find it difficult when they have to create one by themselves. So even before we attempt to create a generics class lets first understand why Generics exist in a language. Lets take a step back and look at the evolution of programming languages,

Before 1980:
    Why do we need functions?
  • Reuse of Code - functions
  • Examples: C
Before 2000:
    Why do we need classes?
  • Reuse of Code - methods
  • Reuse of Data - members
  • Examples: Java < 5 and C# < 2
After 2000:
    Why do we need generics?
  • Reuse of Code - methods
  • Reuse of Data - members
  • Reuse of Types - generic parameters

So as programming languages evolved people started to notice the need for reuse at different levels. To understand specifically about generics and  "Reuse of types". Lets take the simplest usecase for generics. Which is collection(or data structures). Lets take stack for example:

In Java,

class Stack<T>
{
    // For simplicity, I am ignoring all the error checking

    private final int MAX_SIZE = 100;
    private int top = -1;
    T[] items = new T[MAX_SIZE]; // bare with me this statement will not work in Java for other reasons(below)

    void push(T item) {
        items[top++] = item;
    }

    T pop() {
        return items[--top];
    }
}

 

Most of you already know that above class can create different "type" of stacks. One for integers and another for strings etc. Unlike normal classes, This is a different form of reuse. Let me elaborate. Using normal classes we can only stamp out multiple copies(Objects) of the class where the internals(meaning the types) are fixed. But with generics, the beauty is, we can stamp out classes with slightly different internals(types). This may sound like we now found our new super power. Yes we did, but we also need to understand how to tame it!


Designing a generic class:

In order to design a generic class effectively the first step is to identify the parts(mainly types) of the class which can be swapped in and out by keeping the structure(methods/code) of the class same. In the above Stack example, if you observe carefully, every stack class needs space(items array) to store the items, it needs a space(top variable) to track the top of the stack. It needs methods(push/pop) to implement the common operations. Out of these three, the top variable is an index in to the array and it denotes the "position" of the top most item of the stack and it has nothing to do with the item itself being stored. So this can have fixed type `int`. But if you consider the array itself, the size of each element of the array in fact depends on the type of element you want to store so you cannot simply pick one type and call it done. In fact, this is the perfect opportunity to introduce generic type "T" whose actual type can be swapped when the object of stack is created. Similarly since the methods now need to work with the item, we carefully swap the input parameter types and return types with "T" accordingly.

The most important thing that beginners may not observe in the above example is, the Stack class itself is not touching the "thing" that is being stored. Meaning, it is not putting a dot operator on the item. So, no where you would see `item.somemethod()` in the above code. The reason for this, the moment you put a dot you are making the Stack "aware" of the "thing" and the stack can no more be applicable to other type of "things". Because the other type of things may not have `somemethod()` on them. In other words, you are making the stack specific and not Generic!

Advanced: In order for a generic class to be able to put a dot on the item/type, the generic parameter T must be bounded. Meaning, we need to tell the compiler that all T's will have the method `somemethod()` on them. This is achieved by making T a bounded parameter as shown below

class MyNewStack<T extends Number>
{
    // Here we are saying T will always be a subclass of Number so MyNewStack in
    // its implementation below can use methods of Number
}

Care must be taken when designing classes with generics because the reusability provided by classes and generics work in a complementary fashion. We can come up with fancy inheritance hierarchies where sub classes tend to reuse super class code/data and at the same time adding generics to these hierarchies will produce type level reusability. This level of complexity is hard for beginners to understand so lets not worry about it here.

Like inheritance, generics is also not applicable to all scenarios, They tend to create this invisible tension between types being used vs the code that is trying to process them. It is a careful balance between both. Hence they are perfectly applicable for data structures so that's why you see the collections framework contain full of generic implementations

By leveraging these fact, You can now create reusability with types.

Now, specific to Java's implementation of generics, it uses a concept called erasure. Meaning JVM has no notion of generics and generic types are erased from byte code, in other words Java bytecode do not understand what a generic class is, this was a design choice that the Java language designers have made when designing generics in to the language for various reasons. In hindsight, this makes some common scenario of using generic more complicated than it should. Unlike Java, In C#, CLR do understand generics at the IL. So there some of the scenarios are more straight forward.

Hope this helps.

Reference: https://www.amazon.com/Java-Generics-Collections-Development-Process



You may also like

  • Dr. Ravi Saripalle
    Published 7d+

The Connection Between a Mother’s Kiss and a Newborn: Emotion, Science, and Sanatana Dharma

The Connection Between a Mother’s Kiss and a Newborn: Emotion, Science, and Sanatana DharmaDear Friends,Recently, a social media influencer shared a heartwarming video that captivated

  • Bade Ramyasri
    Published 6d

Crafting Your Teacher Identity

Crafting Your Teacher Identity: Defining Your Educational Philosophy"Teaching is not a profession; it's a passion. Without passion for your subject and for your students, you will never be

  • Dr. Ravi Saripalle
    Published 5d

The Cost of Wasted Time: A Reflection on Networking, Focus, and Productivity

The Cost of Wasted Time: A Reflection on Networking, Focus, and ProductivityDear Friends,Recently, I came across a post on X by Naval Ravikant that said, “Networking is overrated. Go do something

  • Tejas
    Published 2d

Greatest Inventions in History : The Steam Engine Revolution: Transforming Society and Industry

The Steam Engine: A Catalyst of Progress and TransformationThe steam engine is more than just a machine; it’s a symbol of human ingenuity and innovation that forever changed the course of history.

  • Edgroom
    Published 7d+

EAPCET Top-20 colleges -- METALLURGICAL ENGINEERING

Top-20 EAPCET colleges for METALLURGICAL ENGINEERING basis EAPCET 2023 cut-off ranks. Cut-off ranks are for OC-Male category from 2022, and 2023 data. You can checks

  • Edgroom
    Published 7d+

EAPCET Top-20 colleges in PUTTUR - COMPUTER SCIENCE AND INFORMATION TECHNOLOGY

Top-20 EAPCET colleges for COMPUTER SCIENCE AND INFORMATION TECHNOLOGY in PUTTUR basis EAPCET 2023 cut-off ranks. Cut-off ranks are for OC-Male category from 2022, and 2023 data.

  • Edgroom
    Published 7d+

EAPCET Top-20 colleges in RAJAM - MECHANICAL ENGINEERING

Top-20 EAPCET colleges for MECHANICAL ENGINEERING in RAJAM basis EAPCET 2023 cut-off ranks. Cut-off ranks are for OC-Male category from 2022, and 2023 data. You

  • Edgroom
    Published 7d+

EAPCET Top-20 colleges in RAMPACHODAVARAM - ELECTRICAL AND ELECTRONICS ENGINEERING

Top-20 EAPCET colleges for ELECTRICAL AND ELECTRONICS ENGINEERING in RAMPACHODAVARAM basis EAPCET 2023 cut-off ranks. Cut-off ranks are for OC-Male category from 2022, and 2023

  • Edgroom
    Published 7d+

EAPCET Top-20 colleges in VISSANNAPETA - PHARMACY(MPC STREAM)

Top-20 EAPCET colleges for PHARMACY(MPC STREAM) in VISSANNAPETA basis EAPCET 2023 cut-off ranks. Cut-off ranks are for OC-Male category from 2022, and 2023 data.

  • Edgroom
    Published 7d+

EAPCET Top-20 colleges in VIJAYAWADA - PHARM.D(MPC STREAM)

Top-20 EAPCET colleges for PHARM.D(MPC STREAM) in VIJAYAWADA basis EAPCET 2023 cut-off ranks. Cut-off ranks are for OC-Male category from 2022, and 2023 data. You

  • Dr. Ravi Saripalle
    Published 7d+

Fascinating Life lessons!

Little things in Life that are Interesting! Fascinating Life lessons!Dear Friends and StudentsThe Amazon rainforest is the largest rainforest in the world, covering an area of approximately 6.7

  • Edgroom
    Published 7d+

EAPCET Top-20 colleges in NARSARAOPET - COMPUTER SCIENCE AND DESIGN

Top-20 EAPCET colleges for COMPUTER SCIENCE AND DESIGN in NARSARAOPET basis EAPCET 2023 cut-off ranks. Cut-off ranks are for OC-Male category from 2022, and 2023 data.