HOME BLOG

Archive for March, 2019

Generic Programming

Posted on: March 16th, 2019 by Olu No Comments

Hi folks,

Today I will like to talk a little bit about a programming pattern I really like. It’s called generic programming.

According to Wikipedia, generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified later that are then instantiated when needed for specific type provided as parameters.

It is useful if you have certain patterns you want to enforce in a class and you want the class to be reusable for arbitrary types of items.

E.g. a grid class that takes a kind of item and can add new item, remove items, etc.

The items it works with all have to be of a certain type.

You can make the class like

class Grid<T> {
    public addItem(item: T) {
        // ...
    }

    public removeItem(item: T) {
        // ...
    }

    public getItems(): T[] {
        // ...
    }
    
}

Note that once you define the generic variable T in the class declaration, you can then later define method input parameters and return types in terms of the generic parameter.

You can then reuse this class for all sorts of items, e.g. books, actors, etc. as follows

const productsGrid = new Grid();
const actorsGrid = new Grid();

This way, when you want to perform actions on your object, the type of input parameters and output can automatically be determined for error checking by your IDE, etc.

So, if you want to write nice reusable classes, a way to consider is generics.

That’s it for now.