Sony
Sony

Reputation: 73

How to reduce cognitive complexity in java code

Please advise how to reduce cognitive complexity on the below code

ids.add((row.getCell(11) != null) ? row.getCell(11).getStringCellValue() : "");

Upvotes: 0

Views: 12698

Answers (2)

Redshift
Redshift

Reputation: 1

You can use Optional:

ids.add(Optional
  .ofNullable(row.getCell(11))
  .map(cell -> cell.getStringCellValue())
  .orElse("")
)

That way you don't need an extra method. If this is something that is needed at many places it is better to create a specific method for at as Andrew S remarked.

Upvotes: 0

Andrew S
Andrew S

Reputation: 2756

Add a method to hide the details, for example:

private String getCellValueOrDefault(Cell cell) {
    if (cell == null) {
       return "";
    }
    return cell.getStringValue();
}

Then use the method:

ids.add(getCellValueOrDefault(row.getCell(11));

Upvotes: 6

Related Questions