vendredi 26 juin 2020

Design pattern / Data structure for a sub-set of data/errors

Several times, I had to return this kind of data structure from a search web service:

[
    {
        "zipCode": "unique criteria", // XOR
        "city": "unique criteria",
        "data": [
            {
                "firstName": "firstName1",
                "lastName": "lastName1"
            },
            {
                "firstName": "firstName2",
                "lastName": "lastName2"
            },
            
            // ....
        ],
        "errors": [
            {
                "code": "ERR_01"
                "message": "Unable to get user 3"
            },
            {
                "code": "ERR_01"
                "message": "Unable to get user 4"
            },
            {
                "code": "ERR_02"
                "message": "Missing required info for user 5"
            },
            
            // ...
    },
    
    // ... (different value for zipCode or city)
]

Note: There is either: zipCode or city but not both. The values are unique.

On the business code I don't know the best way to handle a set of elements/errors.

Currently I plan using a Map with zipCode or city as the key since it is easily distinguishable and the values unique. Full type: Map<String, Set<? extends IFailableData>>. Sadly, IFailableData will be a marker interface (in this case, is this "anti-pattern" relevant?).

           +---------------+
           | IFailableData |
           +---+---------+-+
               ^         ^
               |         |
+--------------+--+   +--+---------+
| SingleErrorImpl |   | SingleData |
+-----------------+   +------------+

Are there design patterns that can solve this common problem or Java helper classes (eg. Optional<?>)?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire