You can enhance the usage of Optional by leveraging its functional methods such as ifPresentOrElse. This approach makes the code more concise, readable, and avoids explicit checks with isEmpty() and get(). Here's how you can refactor your method:
@Override
public void updateOnDequeueCompleted(final EntityReference logisticUnitReference) {
taskQueueDequeueProcessRepository
.findByLogisticUnitRef(logisticUnitReference)
.ifPresentOrElse(
TaskQueueDequeueProcess::confirmDequeueCompleted,
() -> logger.info("Queue Dequeue Process not found for logistic unit {}", logisticUnitReference)
);
}
Explanation:
-
Remove Explicit Optional Variable:
Instead of assigning the result to an Optional variable, chain the methods directly. This reduces the number of lines and keeps the logic streamlined.
-
Use ifPresentOrElse:
ifPresentOrElse takes two arguments:
- A
Consumer that executes if the Optional contains a value.
- A
Runnable that executes if the Optional is empty.
- In this case:
- If the
TaskQueueDequeueProcess is present, it calls confirmDequeueCompleted.
- If not, it logs the information message.
-
Method Reference:
TaskQueueDequeueProcess::confirmDequeueCompleted is a method reference that makes the code cleaner and more readable compared to using a lambda expression.
Benefits:
- Readability: The intent of the code becomes clearer by expressing the action for both presence and absence of the value in a single statement.
- Safety: Avoids potential
NoSuchElementException that might occur if get() is called without checking.
- Conciseness: Reduces boilerplate code by eliminating the need for explicit
if-else blocks.
Alternative with ifPresent and orElse:
If you're using a Java version prior to Java 9, which doesn't support ifPresentOrElse, you can achieve similar functionality using ifPresent combined with an else statement:
@Override
public void updateOnDequeueCompleted(final EntityReference logisticUnitReference) {
Optional<TaskQueueDequeueProcess> queueDequeueProcess =
taskQueueDequeueProcessRepository.findByLogisticUnitRef(logisticUnitReference);
queueDequeueProcess.ifPresent(TaskQueueDequeueProcess::confirmDequeueCompleted);
if (queueDequeueProcess.isEmpty()) {
logger.info("Queue Dequeue Process not found for logistic unit {}", logisticUnitReference);
}
}
However, using ifPresentOrElse is generally more elegant and preferred in newer Java versions.