I have the following 2 methods (some codes omitted for brevity) in my Java (Spring) app and I want to reduce duplicated blocks in these methods. At this point, after making some research, some people suggesting Builder Pattern, some of them another similar one Template Method. I also think that, I could simply create 2 separate methods and move each repeated code blocks to these methods.
However, I have no experience about this issue and I would like to ask you first to follow the most proper ways. So, how should I reduce the code duplication in the following 2 methods? I also think to use inheritance, but I am really confused with finding a proper way.
Not: I omitted my code and use a simple code for brevity:
@Override
public MultipartFile exportAaaaa() throws IOException {
// repeated code block I
workbook = new XSSFWorkbook();
sheet = workbook.createSheet(TextBundleUtil.read(TITLE));
rowCount = new AtomicInteger(0);
//
// private block to this method
final Page<Aaaaa> page = aaaaaService.findAll());
// ...
// repeated code block II
outputFile = File.createTempFile(TextBundleUtil.read(TITLE), EXTENSION);
try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
workbook.write(outputStream);
} catch (IOException e) {
LoggingUtils.error("Writing is failed ", e);
}
final FileInputStream input = new FileInputStream(outputFile);
final String fileName = TextBundleUtil.read(TITLE).concat(EXTENSION);
return new MockMultipartFile(fileName,
fileName, CONTENT_TYPE, IOUtils.toByteArray(input));
//
}
@Override
public MultipartFile exportBbbbb() throws IOException {
// repeated code block I
workbook = new XSSFWorkbook();
sheet = workbook.createSheet(TextBundleUtil.read(TITLE));
rowCount = new AtomicInteger(0);
//
// private block to this method
final Page<Bbbbb> page = bbbbbService.findAll());
// ...
// repeated code block II
outputFile = File.createTempFile(TextBundleUtil.read(TITLE), EXTENSION);
try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
workbook.write(outputStream);
} catch (IOException e) {
LoggingUtils.error("Writing is failed ", e);
}
final FileInputStream input = new FileInputStream(outputFile);
final String fileName = TextBundleUtil.read(TITLE).concat(EXTENSION);
return new MockMultipartFile(fileName,
fileName, CONTENT_TYPE, IOUtils.toByteArray(input));
//
}
Aucun commentaire:
Enregistrer un commentaire