dimanche 19 juin 2022

Polymorphism on a REST service

I am trying to clean and refactor my service code which currently looks like this-

public void generateBalance(Receipt receipt) {

if (receipt.getType().equals(X) && receipt.getRegion.equals(EMEA)) {

// do something to the receipt that's passed 

} else if (receiptType.equals(Y)) {

// do something to the receipt 

} else if (receipt.getRegion.equals(APAC) {
// call an external API and update the receipt
}....

...
// finally

dataStore.save(receipt);

Basically there's a bunch of conditionals that are in this main service which look for certain fields in the object that is being passed. Either it's the type or the region.

I was looking to use this design pattern- https://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html However, I am not sure how this would work for a service class. Currently my REST handler calls this particular service. Also how can I do polymorphism for both the "receiptType" and "region"?

Is there a way I can just do all the updates to the receipt once in different services, then finally save the receipt at one location? (maybe a base class?) I am really confused on how to start. TIA!

Aucun commentaire:

Enregistrer un commentaire