There are 2 functions which have the same piece of code except one line.
public ResponseEntity<String> deleteJob(String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobGroup, jobName);
if (!schedulerFactoryBean.getScheduler().checkExists(jobKey))
return new ResponseEntity<>(format(JOBNAME_JOBGROUP_COMMON_LOG.concat("does not exists"), jobName, jobGroup), HttpStatus.BAD_REQUEST);
schedulerFactoryBean.getScheduler().deleteJob(jobKey);//Different Code line
return new ResponseEntity<>(format(JOBNAME_JOBGROUP_COMMON_LOG.concat("deleted Successfully"), jobName, jobGroup), HttpStatus.OK);
}
public ResponseEntity<String> resumeJob(String jobName, String jobGroup) throws SchedulerException {
JobKey jobKey = JobKey.jobKey(jobGroup, jobName);
if (!schedulerFactoryBean.getScheduler().checkExists(jobKey))
return new ResponseEntity<>(format(JOBNAME_JOBGROUP_COMMON_LOG.concat("does not exists"), jobName, jobGroup), HttpStatus.BAD_REQUEST);
schedulerFactoryBean.getScheduler().resumeJob(jobKey);//Different Code line
return new ResponseEntity<>(format(JOBNAME_JOBGROUP_COMMON_LOG.concat("deleted Successfully"), jobName, jobGroup), HttpStatus.OK);
}
I want to remove the duplicate code from both functions.
A straightforward solution would be to write a third common function and call it from both functions.However I was looking if there is a way ,I could use Lambda expression to pass the code functionality which is different.
Something like
public ResponseEntity<String> processJob(String jobName, String jobGroup, Function<String,String> jobfunction) {
JobKey jobKey = JobKey.jobKey(jobGroup, jobName);
if (!schedulerFactoryBean.getScheduler().checkExists(jobKey))
return new ResponseEntity<>(format(JOBNAME_JOBGROUP_COMMON_LOG.concat("does not exists"), jobName, jobGroup), HttpStatus.BAD_REQUEST);
jobfunction.apply(jobKey);//Apply the required code behaviour
return new ResponseEntity<>(format(JOBNAME_JOBGROUP_COMMON_LOG.concat("deleted Successfully"), jobName, jobGroup), HttpStatus.OK);
}
and then call the function as
processJob(jobName,jobGroup, <lambda expression with delete/resume function calling>)