Created
December 3, 2016 18:05
-
-
Save jbrains/ff3065f4abe0d8d0a7effb8f86c1b122 to your computer and use it in GitHub Desktop.
PLEASE tell me that there's a better way in Java to write this
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// findPrice : String -> Option<Price> | |
// Option comes from Atlassian's fugue library https://docs.atlassian.com/fugue/4.3.0/fugue/apidocs/index.html | |
// I want the equivalent of | |
// case (maybePrice) { | |
// none => display.displayProductNotFoundMessage(barcode) | |
// some(price) => display.displayPrice(price) | |
// } | |
catalog.findPrice(barcode) | |
.<Runnable>fold( | |
() -> (() -> display.displayProductNotFoundMessage(barcode)), | |
(price) -> (() -> display.displayPrice(price)) | |
).run(); |
My two minutes attempt, using Functional Java. Obviously, untested and from the top of my head!
/*
* Assuming:
*
* barcode :: Barcode
* display#displayProductNotFoundMessage() :: F<Barcode, IO<Unit>>
* display#displayPrice() :: F<Price, IO<Unit>>
*/
catalog.findPrice(barcode) // Option<Price>
.map(display.displayPrice()) // Option<IO<Unit>>
.orSome(
display.displayProductNotFoundMessage().f(barcode) // IO<Unit>
)
.run();
If the only side effect is printing a String, we could simplify it like this:
/*
* Assuming:
*
* barcode :: Barcode
* display#displayProductNotFoundMessage() :: F<Barcode, String>
* display#displayPrice() :: F<Price, String>
*/
String res = catalog.findPrice(barcode) // Option<Price>
.map(display.displayPrice()) // Option<String>
.orSome(
display.displayProductNotFoundMessage().f(barcode) // String
);
fancyPrint(res);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@gtrefs Thank you. Yes. I have a separate project in which I'm rewriting my entire teaching example with the constraint "no method expectations in the tests", which encourages me to use return values in the way that you describe here (and even pushing
Display
up the call stack, where it becomesRenderResultView
). In that situation, I think of the situation as mappingOption<Price>
toEither<String, Price>
and then toEither<ProductNotFoundMessage, ProductFoundMessage>
. Now the Controller and View negotiate over who dispatches from the message alternatives to send the corresponding message text to the application's output stream.This is not that project. I'm still using my old, OO approach (fire the right event for each outcome), but I found Fugue (and now Javaslang) intriguing, and so I'm trying to use them together. I can't tell whether the libraries are missing something useful or they're telling me that these types and the fire-event approach are fundamentally incompatible. That's one of the things I'm learning.