Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is type code?

I'm reading "Refactoring" by Martin Fowler.

There is a term "type code" that I've never seen that before.

What is a type code?

like image 832
Winter Singha Avatar asked Oct 29 '25 13:10

Winter Singha


2 Answers

One context in which a type code can appear is in C with a union type:

typedef enum Type { T_INT, T_FLOAT, T_DOUBLE, T_LONG } Type;

typedef struct Datum
{
    Type type;
    union
    {
        int     i;
        float   f;
        long    l;
        double  d;
    } u;
} Datum;

This leads to code like:

Datum v;

switch (v.type)
{
case T_INT:
    int_processing(v.u.i);
    break;
case T_FLOAT:
    float_processing(v.u.f);
    break;
case T_DOUBLE:
    double_processing(v.u.d);
    break;
}

Now, was the omission of T_LONG from the switch deliberate or not? Was it recently added and this switch didn't get the necessary update?

When you get a lot of code like that, and you need to add T_UNSIGNED, you have to go and find a lot of places to correct. With C, you don't have such a simple solution as 'create a class to represent the type'. It can be done, but it takes (a lot) more effort than with more Object Oriented languages.

But, the term 'type code' refers to something like the Type type in the example.

like image 82
Jonathan Leffler Avatar answered Oct 31 '25 12:10

Jonathan Leffler


One context in which a type code can appear is in C with a union type:

typedef enum Type { T_INT, T_FLOAT, T_DOUBLE, T_LONG } Type;

typedef struct Datum
{
    Type type;
    union
    {
        int     i;
        float   f;
        long    l;
        double  d;
    } u;
} Datum;

This leads to code like:

Datum v;

switch (v.type)
{
case T_INT:
    int_processing(v.u.i);
    break;
case T_FLOAT:
    float_processing(v.u.f);
    break;
case T_DOUBLE:
    double_processing(v.u.d);
    break;
}

Now, was the omission of T_LONG from the switch deliberate or not? Was it recently added and this switch didn't get the necessary update?

When you get a lot of code like that, and you need to add T_UNSIGNED, you have to go and find a lot of places to correct. With C, you don't have such a simple solution as 'create a class to represent the type'. It can be done, but it takes (a lot) more effort than with more Object Oriented languages.

But, the term 'type code' refers to something like the Type type in the example.

like image 44
Jonathan Leffler Avatar answered Oct 31 '25 11:10

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!