Don’t put code block in Optional

1. Introduction

In previous few articles we have seen how not to use Optional and explored few areas by refactoring code in better way rather than using Optional. In this article I will talk more on that topic. Gist of this article is do not put any code block in ifPresent method of Optional class. Let us begin.

2. Content

The use case of this article is we have List<Transaction> with details about already processed transactions. We want to log the invoice ids.

3. ifPresent method code smell

It is not uncommon to see Optional being misused but I would say that putting entire code block into ifPresent method takes it to whole new level. 🙂

ifPresent method is used to invoke a consumer on value if value is present in Optional, else do nothing.

But using code blocks inside ifPresent is another code smell for 2 reasons; First, the code looks ugly and secondly we are treating Optional container as a computation block.

Optional.of(transactions)
        .filter(txns -> !txns.isEmpty())
        .ifPresent(txns -> {
            String paidInvoices = 
                        txns.stream()
                            .map(txn -> txn.invoice()
                                           .invoiceTotal()
                                           .toString())
                            .collect(Collectors.joining(","));
 
            logger.log(Level.INFO, paidInvoices);
  });

2.2. Use if condition

It is better to write code without Optional as the usage of Optional is not required for this use case.

if(!transactions.isEmpty()) {
    String paidInvoices = 
                  transactions.stream()
                              .map(txn -> txn.invoice()
                                             .invoiceTotal()
                                             .toString())
                              .collect(Collectors.joining(","));
    logger.log(Level.INFO, paidInvoices);
}

3. Conclusion

ifPresent method is used to invoke a consumer on value if the Optional has a value else it does nothing. Keep the method simple. Don’t complicate stuff by jamming unnecessary things into it.

Leave a Reply

Your email address will not be published. Required fields are marked *