-
-
Save jbrains/2f4b038806edeb3638b637a1ac48ca5f to your computer and use it in GitHub Desktop.
public CommandResponse onBarcode(String barcode) { | |
Price price = catalog.findPrice(barcode); | |
return price == null | |
? new ProductNotFoundMessage(barcode) | |
: new ProductFoundMessage(price); | |
} |
public CommandResponse onBarcode(String barcode) { | |
return catalog.findPrice(barcode) | |
.<CommandResponse> flatMap(price -> Optional.of(new ProductFoundMessage(price))) | |
.orElse(new ProductNotFoundMessage(barcode)); | |
} |
You can use map
instead of flatMap
:
public CommandResponse onBarcode(String barcode) {
return catalog.findPrice(barcode)
.<CommandResponse> map(ProductFoundMessage::new)
.orElse(new ProductNotFoundMessage(barcode));
}
And if you create a static factory method for ProductFoundMessage
that returns an instance of CommandResponse
you can get rid of the ugly type specifier.
Thanks, @tumbarumba. Almost. On Java 8 update 112 I have to explicitly specify the type CommandResponse
, otherwise Java infers the wrong type for the "or else" branch.
public CommandResponse onBarcode(String barcode) {
return catalog.findPrice(barcode)
.<CommandResponse> map(ProductFoundMessage::new)
.orElseGet(() -> new ProductNotFoundMessage(barcode));
}
I didn't understand this when I first tried to write the code, so that might explain how I ended up going down the flatMap()
road.
@nicolaiparlog Even better! Thanks. Yes: I might consider a factory method, although that would annoy me, since, in a sense, that's a big part of the point of this class. :)
If I didn't miss anything, it seems that catalog#findPrice
returns Optional
?
I prefer to not have Optional
as a return type (nor as a parameter for that matter) for (at least) these reasons:
- have to change or wrap existing APIs
- the
Optional
instance can also benull
(the Java language enables it ;)) so not really solving the problem
I prefer to use Optional.ofNullable
.
FlatMap usage looks a bit weird. Perhaps this is what you're looking for?