Wednesday 7 August 2019

Best practices while parsing downstream response with enum value

Enums are always been the contract between the API (service) and its client(s). But if at all it is required to enhance the enum (add a new value) from API side, it is almost impossible to inform about the change to all its client(s). At the end, if the client implementation is not backward compatible it fails to parse the API response.

Example – 1:
Here when we try to parse API response with a new enum value it ends up with below exception.
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `Status` from String "INTERMEDIATE": value not one of declared Enum instance names: [START, END] at [Source: (String)"{"status": "INTERMEDIATE"}"; line: 1, column: 12] (through reference chain: Resp["status"])

We can avoid such situation by making our client code backward compatible by following few best practices:

Method - I : By replacing the invalid value by some default enum constant
Always define a default enum value like EMPTY or INVALID or DEFAULT or UNKNOWN or _ etc. based on the best suitable
Test Cases:

Method - II : By setting the below deserialization feature to ObjetMapper object
Test Case:

Pros N Cons of the above two methods

  • Method - I gives you a default enum constant which is NULL safe and you can easily ignore this through out your code.
  • Method - II gives you a NULL which prone to NullPointerException