I am working on code written few years back. It builds POJO out of JSON. JSON has a statusType
field. Value of all other fields are dependent on statusType
field. If statusType
is SUCCESS
, fields successCode
, totalValue
, concession
etc are populated, on the other hand if it is FAILURE
, fields errorCode
, exceptionType
, retryCounts
are populated.
{
"statusType": "SUCCESS",
"successCode": "20.304",
"total": 1000
}
{
"statusType": "FAILED",
"errorCode": "50.31",
"retryCounts": 2
}
POJO is defined like following:
public class JsonPOJO {
public String statusType;
public String successCode;
public int retryCounts;
public int total;
public String errorCode;
}
Client code is like following:
JsonPOJO pojo = buildPojo();
if (pojo.getStatusCode.equals(“SUCCESS”)) {
String successCode = pojo.getSuccessCode();
} else {
String errorCode = pojo.getErrorCode();
}
Above code is scattered throughout (around 10 places). Very soon, we'll be getting another status code "IN_PROGRESS"
, which will introduce few more fields in JSON and then POJO will have few more fields and consequently more if/else statements throughout the code checking for statusType
. I don't want to go through this route. I want to elegantly refactor code, so that if I get another status code (for example, "SUSPENDED"
), I need not touch whole codebase again.
I couldn't find (maybe my Googling skills suck) any pattern, in general, to handle this kind of situation, so I am reaching out to experts here for their opinions/thoughts.