If I have a similar block of code that is used in many places with different functionality but contains return statements, how can I restructure it to make this block into a function? For example, lets say I have an object Mailman that contains a validity code (success/fail/reason for failure) and also possibly a package to give the callee.
In one case the mailman might just grab his item that's held and give it to the callee:
Mailman mailman = requestMailForPerson(person);
switch(mailman.getStatus()){
case SUCCESS:
Mail mail = (Mail)mailman.getHeldItem();
return Response.ok().entity(mail).build();
case PERSON_DOESNT_EXIST:
return Response.status(Response.status.BAD_REQUEST).build();
case MAIL_SERVICE_FAILED_SOMEWHERE:
return Response.status(Response.status.INTERNAL_SERVER_ERROR).build();
}
But in another he might be rerouting a letter
Mailman mailman = rerouteLetterForPerson(letter, person);
switch(mailman.getStatus()){
case SUCCESS:
Letter letter = (Letter)mailman.getHeldItem();
if(distance(letter.address, currentLocation) > 50){
sendToNextoffice(letter);
return Response.ok.entity("in transit").build();
}else{
return Response.ok().entity(letter).build();
}
case PERSON_DOESNT_EXIST:
return Response.status(Response.status.BAD_REQUEST).build();
case MAIL_SERVICE_FAILED_SOMEWHERE:
return Response.status(Response.status.INTERNAL_SERVER_ERROR).build();
}
There are just blocks of code that look really similar, and I want to break out this logic somewhere, but handling the different success/fail scenarios is giving me a hard time.
Aucun commentaire:
Enregistrer un commentaire