Skip to content

Instantly share code, notes, and snippets.

@jbrains
Created November 27, 2016 20:11
Show Gist options
  • Save jbrains/2f4b038806edeb3638b637a1ac48ca5f to your computer and use it in GitHub Desktop.
Save jbrains/2f4b038806edeb3638b637a1ac48ca5f to your computer and use it in GitHub Desktop.
I'm not convinced by this particular usage of Optional...
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));
}
@tumbarumba
Copy link

FlatMap usage looks a bit weird. Perhaps this is what you're looking for?

    public CommandResponse onBarcode(String barcode) {
        return catalog.findPrice(barcode)
                .map(ProductFoundMessage::new)
                .orElseGet(() -> new ProductNotFoundMessage(barcode));
    }

@nipafx
Copy link

nipafx commented Nov 27, 2016

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.

@jbrains
Copy link
Author

jbrains commented Nov 27, 2016

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.

@jbrains
Copy link
Author

jbrains commented Nov 27, 2016

@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. :)

@mbjelac
Copy link

mbjelac commented Nov 28, 2016

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 be null (the Java language enables it ;)) so not really solving the problem

I prefer to use Optional.ofNullable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment