Search code examples
refactoringterminology

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?


Solution

  • 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.