0
votes

I am writing to Excel using Apache POI based on the contents of my DB. I have the below code which works correctly, if the cell is null in my DB then it sets it as blank in the Excel cell.

However, because I have several if else statements, its failing Sonar Lint analysis (cognitive complexity needs to be reduced, which means I need to remove some of the if else statements). I've only had to apply these checks for Double and Object types.

After some research I think the best way to resolve this is to create a missing cell policy (create null as blank), but I am finding to hard to say if the field is null then setCellValue as missingCellPolicy.

How can I do this?

List<CaseData> cases = (List<CaseData>) model.get("cases");
    Sheet sheet = workbook.createSheet("PIE Cases");

int rowCount = 1;
    for (CaseData pieCase : cases) {
        Row userRow = sheet.createRow(rowCount++);

if (pieCase.getActualAmountReturned() == null) {
            userRow.createCell(2).setBlank();
        } else {
            userRow.createCell(2).setCellValue(pieCase.getActualAmountReturned());
        }
if (pieCase.getChannel() == null) {
            userRow.createCell(9).setBlank();
        } else {
            userRow.createCell(9).setCellValue(pieCase.getChannel().getChannel());
        }
1
just check if value is != null and only then create the cell. removes 50% of your il/else - XtremeBaumer
If any tool tells me that I should not use as much if - else statements as were needed to fulfill the requirements, then I would not trust that tool much. If the tool knows how many if - else statements are needed to fulfill the requirements, why the tool then is not able creating the code for me? - Axel Richter

1 Answers

2
votes

You can do this, will work fine

List<CaseData> cases = (List<CaseData>) model.get("cases");
    Sheet sheet = workbook.createSheet("PIE Cases");

int rowCount = 1;
    for (CaseData pieCase : cases) {
        Row userRow = sheet.createRow(rowCount++);

if (pieCase.getActualAmountReturned() != null) {
           userRow.createCell(2).setCellValue(pieCase.getActualAmountReturned());
}
if (pieCase.getChannel() != null) {
            userRow.createCell(9).setCellValue(pieCase.getChannel().getChannel());
}