Pergunta

Backgound info

In a product I am working on we have a lot of enumerated values for storing the "type" of a piece of data. For example (this stuff lives in C in a microcontroller):

typedef enum
{
    Temperature     = 100,
    InputVoltage    = 200,
    AverageVoltage  = 201,
    Current         = 300,
} ReadingType_t;

This allows us to handle "readings" generically, kind of like this:

typedef struct
{
    ReadingType_t type;
    sint32_t      value;
} Reading_t;

Reading_t readings[5];
readings[0].type = Temperature;
readings[0].value = 25; // in degrees C
readings[1].type = InputVoltage;
readings[1].value = 4321; // in milliVolts

The Problem

I am trying to specify a JSON-based API for outputting information of this form. Some of the possible formats I have include:

readings = [
    {
        "type": "Temperature",
        "value": 25
    },
    {
        "type": "InputVoltage",
        "value": 4321,
    }
]

or

readings = [
    {
        "type": 100,
        "value": 25
    },
    {
        "type": 200,
        "value": 4321,
    }
]

or

readings = [
    {
        "type": {
            "code": 100,
            "name": "Temperature"
        },
        "value": 25
    },
    {
        "type": {
            "code": 200,
            "name": "InputVoltage"
        },
        "value": 4321,
    }
]

Assumptions

I am assuming that the API generates JSON.

I am assuming the API will be consumed by a Javascript client application and/or consumed directly for debugging.

Questions

The questions that I have are:

  1. Should I include the enumeration "code", "title" or both? Is there an accepted practice for this?
  2. If I include the "title" should it be in a regular language format? i.e. should I have "InputVoltage" or "Input Voltage"?
  3. How should I go about supporting Internationalisation vs ease of consumption? i.e.:
    • If I send the numeric "code" there is no confusion about what the type is BUT a lookup table has to be used to get a human usable string (with a different table being used for internationalisation)
    • If I send the string "title" in regular language format the API must do the internationalisation (which is fine) BUT then we cannot do any logic based on that value (because the "title" will change based on the language whereas the code will not).
Foi útil?

Solução

I would strongly advise against including the code as well as the name in the output. It is redundant, it ties you too much to both the code and the name being valid as long as you want to support reading/writing of the data.

I would recommend outputting the name to the file. The code is an implementation detail that could change in the future. Today you have an enum, tomorrow you could have a hash table. But the name is a meaningful information that, most likely, won't change.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top