Is it possible to rewrite the following using Optional ? It seems to me when the situation requires to throw exception then using Optional may not be a good idea ?
Item item = service.get(id);
if (item == null) {
throw new ItemNotFoundException();
}
item.setValue(false);
itemDao.update(item);
Attempt 1:
Optional.ofNullable(service.get(id))
.ifPresent(item -> {
item.setValue(false);
itemDao.update(item);
}); // cannot throw exception inside the consumer
Attempt 2:
Optional.ofNullable(service.get(id))
.map(item -> {
item.setValue(false);
itemDao.update(item);
})
.orElseThrow(new ItemNotFoundException()); //can throw exception here but the usage of map is not correct