“This is the 17th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge in 2021”.
background
Yes, I am still working on XXXX project, and I am still working on docking interface with a third party. The difference is that this time I am dealing with my own business logic.
One of the problems I encountered during development was:
Table structure: A primary table A, an associated table B, table A stores the state of the records in table B.
Scenario: Step 1 Create primary table data and insert table A. Step 2 insert table B using A third-party interface and update the status of table A. At this point, you probably think about the idempotent nature of the data in step 2. In this case, there will be the following situations:
1. If no data associated with table A exists in Table B, the third-party interface needs to be invoked to insert table B and update the status of table A.
2. Data associated with Table A exists in Table B;
- The state in table A is in process: the words in process are returned directly;
- The status in table A is processing success: the message “success” is returned directly.
- If the status in table A is failed, you need to invoke the third-party interface to update table B and update the status of table A.
Code implementation
The first thing I did was write pseudocode like this
B b = this.baseMapper.selectOne(queryWrapper);
if(b ! =null) {
String status = b.getStatus();
if (Objects.equals(Constants.STATUS_ING, status)){
return "In process";
} else if (Objects.equals(Constants.STATUS_SUCCESS, status)){
return "Processed successfully";
}
// Failed operation
// Request a third-party interface and parse the response.if (ReturnInfoEnum.SUCCESS.getCode().equals(parse.getCode())) {
......
// Update table B operations
bb.setStatus(Constants.STATUS_ING);
mapper.updateById(bb);
// Update the status of table Aa.setStatus(Constants.STATUS_ING); aMapper.updateById(a); }}else {
// Request a third-party interface and parse the response.if (ReturnInfoEnum.SUCCESS.getCode().equals(parse.getCode())) {
......
// Insert table B
bb.setStatus(Constants.STATUS_ING);
mapper.insert(bb);
// Update the status of table Aa.setStatus(Constants.STATUS_ING); aMapper.updateById(a); }}Copy the code
I wonder if you have noticed that the situation where table B records exist and the state is “failed” and the situation where table B does not exist are the same except for the operation of inserting or updating table B.
How would you refactor that code? Think about it, and we’ll give you a solution below. If you have different opinions or better idea, welcome to contact AH Q, add AH Q can join the technical exchange group to participate in the discussion!